13

contextMenu は行に依存しているため、ContextMenu が表示される前に右クリックして dataGridView の行を選択する必要があります。

私はこれを試しました:

 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 に答える
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 に答える