不能使任何DataGridViewCellEventHandler事件工作

本文关键字:事件 工作 DataGridViewCellEventHandler 任何 不能 | 更新日期: 2023-09-27 18:02:14

我一直在尝试很多不同的方法来尝试触发事件基于点击在我的datagridview。首先,我想从MDN提出一个基本的例子,然后我想把一些我正在使用的另一个点击事件的工作,希望有人能解释我做错了什么,为什么一种方式是工作而另一种不工作。

    public event DataGridViewCellMouseEventHandler CellMouseClick;
    private void DataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        System.Text.StringBuilder cellInformation = new System.Text.StringBuilder();
        cellInformation.AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex);
        cellInformation.AppendLine();
        cellInformation.AppendFormat("{0} = {1}", "RowIndex", e.RowIndex);
        cellInformation.AppendLine();
        MessageBox.Show(cellInformation.ToString(), "CellMouseClick Event");
    }

请注意,我也试过删除这个公共事件调用。此外,我得到一个工具提示,显示在公共事件调用的CellMouseClick部分,说我从来没有使用CellMouseClick项。

对于另一个鼠标点击事件,我想检测,下面设法工作,但它似乎需要更多的让它工作,上面似乎应该工作如此无缝,所以我宁愿让上面的工作,因为它是有意的。以下是工作版本。

public Form1()
    {
        InitializeComponent();
        this.dataGridView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGridView_MouseDown);
        this.toolStripMenuItem1.Click += new System.EventHandler(this.toolStripMenuStrip1_Click);
    }
private void dataGridView_MouseDown(object sender, MouseEventArgs e)
    {
        var hti = dataGridView1.HitTest(e.X, e.Y);
        if (e.Button == MouseButtons.Right)
        {
            try
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[hti.RowIndex].Selected = true;
                this.dataGridView1.CurrentCell = this.dataGridView1.Rows[hti.RowIndex].Cells[1];
                this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
                contextMenuStrip1.Show(Cursor.Position);
            }
            catch (Exception)
            {
            }
        }
    }

不能使任何DataGridViewCellEventHandler事件工作

以上代码正常工作。我试过了。因为我没有完整的代码,所以很难确切地知道哪里出了问题。

需要注意的一点是,catch(异常)实际上并不做任何事情,导致任何异常只是不加通知地传递。你可能有一些例外。尝试打印异常信息或优雅地处理任何异常。

         catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

嗯,经过一段时间的寻找,我终于找到了真正的答案。

我不太记得我是在哪里找到它的,但我错过的是这个调用:

    dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;

MSDN网站似乎表明这是在事件处理程序之前进行的调用:

    public event DataGridViewCellMouseEventHandler CellMouseClick;

这两个的梯子不起作用。如果上面那个尝试回答这个问题的人确实做到了,我可以想象用户根据经验添加了一些他们知道应该添加的东西,并且可能认为我在做这件事。因此,为了清楚起见,这里是导致事件工作的最终产品:

     public Form1()
    {
        InitializeComponent();
        dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        //whatever you want to happen when the mouse is clicked in a cell.
    }
相关文章: