为什么我的DataGridView中没有这个Button点击?

时间:2017-02-24 16:20:42

标签: c# winforms events button 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;
    }
}

我已尝试添加其他Click事件以查看它们如何与此进行交互,它们似乎正常运行。

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", "", "");
    }
}

1 个答案:

答案 0 :(得分:2)

尽量不要在2 = 3事件处理程序中设置var 2 = function() {}的{​​{1}}属性。

由于您使用单个Visible为整个Button控件创建并只是更改其位置,因此您无需处理CellMouseLeave事件。这对我有用:

Button