Search code examples
.netdatagridviewcell

How To Select multiple cells in DataGridView


I have a DataGridView in my Form. The Functionality is as below.

  • Clicking on header selects the whole column.
  • Clicking on any cell other than the column header selects the entire row

I have set multiselect to true. I am able to select multiple cells by using the mouse. but I want to do it programmatically.


Solution

  • If you have multiselect true for your DataGridView then you can loop through the grid and the set the desired row as Selected

    (Also your dataGridView.SelectionMode should be FullRowSelect)

    dataGridView.Rows[0].Selected = true;//determine index value from your logic
    dataGridView.Rows[5].Selected = true;
    

    EDIT

    Instead of row select then you can try this logic, subscribe to the rowheaderclick event wherein you would get the row index for which it was clicked, now loop through the columns and set each cell as selected (similar to above)

    In the same way for the HeaderClick event you would have the column index available, now loop row wise and set the row indexes selected.

    datagridview1[columnindex, rowindex].Selected = true
    

    For rows the rowindex would be fixed whereas for column select the columnindex would be fixed.

    Hope this helps you.