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这是有道理的。感谢您的解释! –