Toggling row selection in a DataGridView...

csharp Madrid, Spain
  • 13 years ago

    Hello Experts,

    I have another problem for which I hope that you guys can provide me a solution. I have a datagridview control on my Windows form application. I would want to toggle the row selection when the user clicks on the row i.e., selected row to unselected row and vice versa.

    I have tried the following code in the dataGridView1_CellClick event, but it does not work:

            private void dgvDataTable_CellClick(object sender, DataGridViewCellMouseEventArgs e)
            {

                //e.RowIndex will give the index of the row clicked on by the user...

                if (dgvDataTable.Rows[e.RowIndex].Selected)
                {
                    dgvDataTable.Rows[e.RowIndex].Selected = false;
                }
                else
                {
                    dgvDataTable.Rows[e.RowIndex].Selected = true;
                }
            }

    Have also tried the above code in the  dataGridView1_CellMouseDown event and it does not work.

            private void dgvDataTable_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
            {
                if (dgvDataTable.Rows[e.RowIndex].Selected)
                {
                    dgvDataTable.Rows[e.RowIndex].Selected = false;
                }
                else
                {
                    dgvDataTable.Rows[e.RowIndex].Selected = true;
                }
            }

     

    Could somebody please help me out with it?

    Thanks in advance,

    Abhisheik. 

     

  • 13 years ago

    Write code in CellClick or CellMouseDown otherwise both methods will work and your condition replies same answer.

            private void dgvDataTable_CellClick(object sender, DataGridViewCellMouseEventArgs e)
            {

                //e.RowIndex will give the index of the row clicked on by the user...

                if (dgvDataTable.Rows[e.RowIndex].Selected)
                    dgvDataTable.Rows[e.RowIndex].Selected = false;
                else
                    dgvDataTable.Rows[e.RowIndex].Selected = true;
            }

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler