Right Click and Auto Row Select with a ContextMenuStrip

If you have a datagridview and want to be able to right-click, which should automatically selecte the row that you’ve clicked and fire the ContextMenuStrip, it can be done as follows:


private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
    if (e.Button == MouseButtons.Right)
        foreach (DataGridViewRow s in dataGridView1.SelectedRows)
            s.Selected = false;
        DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
        dataGridView1.Rows[hit.RowIndex].Selected = true;
        dataGridView1.CurrentCell= dataGridView1.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
        contextMenuStrip1.Show(dataGridView1, new Point(e.X,e.Y) );

What's your thoughts on this?


Protected by WP Anti Spam