【问题标题】:Left and Right Mouse click event for a cell in a DataGridViewDataGridView 中单元格的鼠标左键和右键单击事件
【发布时间】:2018-08-02 10:44:56
【问题描述】:

我正在尝试获取一个事件,如果您左键单击DataGridView 中的一个单元格,该单元格的内容将进入Textbox。如果您右键单击DataGridView 中的单元格也是如此,内容将进入不同的Textbox。这是我到目前为止的代码

  private void dataGridView2_mirror_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        switch (MouseButtons)
        {
            case MouseButtons.Left:
                textBox3.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                break;

            case MouseButtons.Right:
                textBox4.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                break;
        }
    }

我遇到的问题是它无法识别单元格正在被单击,就像我将代码放入常规的MouseEventArgs 以使鼠标按下代码将识别它是右键单击还是左键单击。

【问题讨论】:

    标签: c# winforms datagridview mouseevent


    【解决方案1】:

    我在下面提出了这个想法。另外我认为最好使用 CellMouseUp 或 CellMouseDown 事件。

    private void dataGridView2_mirror_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
            {
                if (e.Button.HasFlag(MouseButtons.Left))
                {
                    textBox3.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    return;
                }
    
                if (e.Button.HasFlag(MouseButtons.Right))
                {
                    textBox4.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    return;
                }
            }
    

    【讨论】:

    • 不客气。我很高兴能在这方面为您提供帮助。
    【解决方案2】:

    您测试的不是当前按钮值,而是枚举本身,它与if (1 == 1).. 相同((或者更准确地说:None == some integer))

    最低限度的解决方法是更改​​为

    switch (e.Button)
    

    但是:MouseButtons 是一个标志枚举,这意味着多个值可以为真。养成只测试你真正想要的标志的习惯,并总是这样测试它们:

    e.Button.HasFlag(MouseButtons.Left)..
    

    这使得使用switch 变得很困难,但是通常只有两个按钮来识别switch 无论如何都没有意义..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多