rafalefighter
rafalefighter

Reputation: 734

Select only one cell in datagridview when rightclick

in my application i have a datagridview with many rows. i want to add a feature to pop up context menu when user right click in certain cell. but only way to select a cell is left click in default. so i searched little bit and i found this code

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Right)
            {
                var hti = dataGridView1.HitTest(e.X, e.Y);
                dataGridView1.ClearSelection();
                dataGridView1.Rows[hti.RowIndex].Selected = true;
            }
        }

but the problem of this code is after i put this code to mousedown when i right click wholw row is selected.but i only want to select one cell

how can i fix this

Upvotes: 0

Views: 2477

Answers (1)

Tea With Cookies
Tea With Cookies

Reputation: 1020

To get the behaviour you want you have to:

-Make sure you have in your dataGridView1 properties SelectionMode = CellSelect or SelectionMode = RowHeaderSelect (depending if you want the user to be able to select the whole row)

-Make these changes on your code:

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var hti = dataGridView1.HitTest(e.X, e.Y);
                if (hti.RowIndex >= 0)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.CurrentCell = dataGridView1[hti.ColumnIndex, hti.RowIndex];
                }
            }
        }

Upvotes: 1

Related Questions