代码之家  ›  专栏  ›  技术社区  ›  Daniel

右键单击以选择数据网格行不工作

  •  1
  • Daniel  · 技术社区  · 8 年前

    我读过一些问题,询问如何在右键单击网格时实现datagridrow选择。答案显示了几种不同的方法来实现它,在很大程度上,除了这个奇怪的错误,它们对我都起了作用。

    该行似乎已被选中,但除非先左键单击该行,否则在选择操作时,第一行始终是选定的行。即,当我单击第3行上的“编辑”时,第1行的数据将传递到“编辑”窗体(除非我在右键单击前左键单击第3行)

    这是右键单击菜单,显示明显的选择:

    enter image description here

    注意,小指示器仍然在第一行。

    如果关闭上下文菜单,则该行看起来已选定,但不是:

    enter image description here

    如果我左键单击同一行,它现在被选中

    enter image description here

    下面是右键单击事件的代码:

    设计师代码:

    MyDataGrid.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
    

    格式代码:

    private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {       
            var hti = MyDataGrid.HitTest(e.X, e.Y);
            MyDataGrid.CurrentCell = MyDataGrid.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
        }
    }
    

    实际选择行缺少什么?

    3 回复  |  直到 8 年前
        1
  •  2
  •   Rob    8 年前

    在中替换代码 MouseDown 事件回拨:

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var hti = dataGridView1.HitTest(e.X, e.Y);
    
            if (hti.RowIndex != -1)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[hti.RowIndex].Selected = true;
                dataGridView1.CurrentCell = dataGridView1.Rows[hti.RowIndex].Cells[0];
            }
        }
    }
    

    下面是它的工作演示:

    enter image description here

        2
  •  0
  •   GuidoG    8 年前

    您可以右键单击行中的焦点行。 CellMouseDown 像这样的事件

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
         DataGridView1.CurrentCell = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    }
    
        3
  •  -1
  •   ataraxia    6 年前

    这是因为右键单击实际上并没有选择您右键单击过的单元格,只有左键单击才能这样做。需要为单元格鼠标向下事件添加处理程序,请将其添加到窗体的设计器中:

    MyDataGridView.CellMouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
    

    并将此添加到表单的类中:

    private void MyDataGridView_MouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        MyDataGridView.CurrentCell = MyDataGridView(e.ColumnIndex, e.RowIndex);
    }
    

    这将设置 CurrentCell 即当前选中的单元格,当光标在 MouseDown 事件被称为。

    推荐文章