1
當我將一行按鈕移動到允許用戶刪除行時,向DataGridView添加一個按鈕。我之前把它作爲一個額外的列,但現在我只想讓按鈕在懸停時顯示出來。該按鈕將自身移動到懸停的行,並放置在最後一列的末尾。爲什麼我的DataGridView中的按鈕沒有點擊?
爲什麼按鈕不能讓我點擊它(事件永遠不會觸發)?
public class CustomDataGridView : DataGridView
{
private Button deleteButton = new Button();
public CustomDataGridView()
{
this.Columns.Add("Column1", "Column1");
this.Columns.Add("Column2", "Column2");
this.Columns.Add("Column3", "Column3");
this.CellMouseEnter += this_CellMouseEnter;
this.CellMouseLeave += this_CellMouseLeave;
deleteButton.Height = this.RowTemplate.Height - 1;
deleteButton.Width = this.RowTemplate.Height - 1;
deleteButton.Text = "";
deleteButton.Visible = false;
deleteButton.MouseClick += (s, e) =>
MessageBox.Show("Delete Button Clicked!", "", MessageBoxButtons.OK);
this.Controls.Add(deleteButton);
}
private void this_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
deleteButton.Visible = true;
Rectangle rect = this.GetCellDisplayRectangle(2, e.RowIndex, true);
deleteButton.Location = new Point(rect.Right - deleteButton.Width - 1, rect.Top);
}
}
private void this_CellMouseLeave(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex != -1)
deleteButton.Visible = false;
}
}
我試過在其他點擊事件中添加它們,看它們如何與它們進行交互,並且它們似乎工作正常。
this.Click += (s, e) =>
MessageBox.Show("DataGridView Clicked!", "", MessageBoxButtons.OK);
this.CellClick += (s, e) =>
MessageBox.Show("Cell Clicked!", "", MessageBoxButtons.OK);
this.MouseClick += (s, e) =>
MessageBox.Show("DataGridView Mouse Clicked!", "", MessageBoxButtons.OK);
this.CellContentClick += (s, e) =>
MessageBox.Show("Cell Content Clicked!", "", MessageBoxButtons.OK);
CustomDataGridView的創作:
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
CustomDataGridView dgv = new CustomDataGridView();
dgv.Location = new Point(100, 100);
dgv.Width = 500;
dgv.Height = 300;
this.Controls.Add(dgv);
dgv.Rows.Add("text1", "", "");
dgv.Rows.Add("text2", "", "");
dgv.Rows.Add("text3", "", "");
dgv.Rows.Add("text4", "", "");
dgv.Rows.Add("text5", "", "");
}
}
哇!這樣簡單的解決方案!我不確定爲什麼要改變這一點,但我很高興你能想出來!謝謝! –
@BlakeThingstad因爲當鼠標移過按鈕時,它會觸發CellMouseLeave事件,該事件隱藏了按鈕,觸發CellMouseEnter事件,該事件顯示按鈕等等。您的代碼太忙而無法顯示和隱藏按鈕做任何事情。 – LarsTech
@LarsTech這是有道理的。感謝您的解釋! –