【问题标题】:Right-click to select DataGrid Row not working右键单击以选择 DataGrid Row not working
【发布时间】:2018-06-08 14:41:47
【问题描述】:

我已经阅读了几个问题,询问如何在右键单击网格时实现 DataGridRow 选择。答案显示了实现它的几种不同方法,并且在大多数情况下,除了这个奇怪的错误之外,它们对我有用。

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

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

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

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

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

这里是右键事件的代码:

设计师代码:

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];
    }
}

我在实际选择行时缺少什么?

【问题讨论】:

  • 作为一个选项,您可以简单地将ContextMenuStrip 分配给一行。此外,如果您希望在显示菜单之前选择行,您可以处理 CellContextMenuStripNeeded 事件。看来this post 就是你要找的。​​span>

标签: c# winforms right-click


【解决方案1】:

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];
        }
    }
}

这是它的工作演示:

【讨论】:

    【解决方案2】:

    您可以像这样在CellMouseDown 事件中使右键单击的行成为焦点行

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
         DataGridView1.CurrentCell = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    }
    

    【讨论】:

    • 谢谢,我还发现我需要添加一个检查以确保 e.RowIndex 和 e.ColumnIndex 不是 -1(如果单击单元格区域之外返回的内容,例如标题)
    【解决方案3】:

    这是因为右键单击实际上不会选择您右键单击的单元格,只有左键单击才会这样做。您需要为单元格鼠标按下事件添加一个处理程序,将其添加到表单的设计器中:

    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 事件时光标所在的单元格。

    【讨论】:

    • 你可以在if (e.Button == System.Windows.Forms.MouseButtons.Right)if (e.Button == System.Windows.Forms.MouseButtons.Right)添加鼠标右键检查
    • @GuidoG 否,因为 OP 使用的是 DataGridView 本身的处理程序,而不是其中的单元格
    • 您的代码无法编译。在发布之前始终对其进行测试。
    • @LarsTech 这是一个简单的名称不匹配,您可以修复我的答案,而不仅仅是告诉我我错了。现已修复。
    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2013-08-22
    • 2022-12-03
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多