13

我需要在显示 ContextMenu 之前右键单击 dataGridView 中的一行,因为 contextMenu 是行相关的。

我试过这个:

 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] 时,我只看到左键选择的行,而不是右键选择的行。

4

4 回答 4

30

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

    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        var dataGrid = (DataGridView) sender;
        if (e.Button == MouseButtons.Right && e.RowIndex != -1)
        {
            var row = dataGrid.Rows[e.RowIndex];
            dataGrid.CurrentCell = row.Cells[e.ColumnIndex == -1 ? 1 : e.ColumnIndex];
            row.Selected = true;
            dataGrid.Focus();
        }
    }
于 2013-05-27T02:28:33.960 回答
3

我意识到这个线程很旧,我只想添加一件事:如果您希望能够在多行上选择并执行操作:您可以检查您右键单击的行是否已被选中。这样,DataGridview 在这方面的行为类似于 ListView。因此,右键单击尚未选择的行:选择该行并打开上下文菜单。右键单击已选择的行只会为您提供上下文菜单并按预期保持所选行。

 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.RowIndex != -1 && e.ColumnIndex != -1)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridViewRow clickedRow = (sender as DataGridView).Rows[e.RowIndex]; 
                if (!clickedRow.Selected)
                    dataGridView1.CurrentCell = clickedRow.Cells[e.ColumnIndex];

                var mousePosition = dataGridView1.PointToClient(Cursor.Position);

                ContextMenu1.Show(dataGridView1, mousePosition);
            }
        }
    }
于 2014-04-07T12:35:43.550 回答
0
    private void grid_listele_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            grid_listele.ClearSelection();
            grid_listele[e.ColumnIndex, e.RowIndex].Selected = true;
        }


    }
于 2014-05-21T21:14:47.740 回答
0
 if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            var hti = GridView.HitTest(e.X, e.Y);
            GridView.ClearSelection();

            int index = hti.RowIndex;

            if (index >= 0)
            {
                GridView.Rows[hti.RowIndex].Selected = true;
                LockFolder_ContextMenuStrip.Show(Cursor.Position);
            }

        }

我猜这是准确的方法

于 2017-05-17T15:17:10.673 回答