右键单击以选择dataGridView中的行 [英] Right click to select row in dataGridView

查看:95
本文介绍了右键单击以选择dataGridView中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在dataGridView中选择一行,右键单击ContextMenu,因为contextMenu是row-dependendt。

I need to select a row in dataGridView with right click before ContextMenu shown because contextMenu is row-dependendt.

我已经尝试过:

 if (e.Button == MouseButtons.Right)
        {

            var hti = dataGrid.HitTest(e.X, e.Y);
            dataGrid.ClearSelection();
            dataGrid.Rows[hti.RowIndex].Selected = true;
        }

或:

private void dataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            dataGrid.Rows[e.RowIndex].Selected = true;
            dataGrid.Focus();
        }
    }

这个工作,但是当我尝试读取dataGrid.Rows [CurrentRow.Index]我只看到左键选择的行,而不是右键单击选中的行。

This works but when I try to read dataGrid.Rows[CurrentRow.Index] I see only the row selected with left click and not those selected with right click..

推荐答案

尝试设置当前选择的单元格(在选择上下文菜单项之前,将设置 DataGridView CurrentRow 属性):

Try setting the current cell like this (this will set the CurrentRow property of the DataGridView before the context menu item is selected):

    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            // Add this
            dataGrid.CurrentCell = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
            // Can leave these here - doesn't hurt
            dataGrid.Rows[e.RowIndex].Selected = true; 
            dataGrid.Focus();
        }

    }

这篇关于右键单击以选择dataGridView中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆