DataGridView: How to select an entire Column and deselect everything else?
Sorry it took so long - I wanted to test before I answered, so I plopped this into Visual Studio to test first.
I had to do this in mine to get it to work:
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
c.SortMode = DataGridViewColumnSortMode.NotSortable;
c.Selected = false;
}
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
dataGridView1.Columns[0].Selected = true;
Loop through the cells in the column and set their Selected property to true.
It sounds horrible, but I believe it's the only way to select an entire column and keep automatic sorting.
For example:
grid.ClearSelection();
for(int r = 0; r < grid.RowCount; r++)
grid[columnIndex, r].Selected = true;
You need 3 things.
- Clear all selected rows and cells.
- Remove the sort mode of every column to Not sortable. The default click event is sort, now it will be select.
- Set the selection mode to column.
Finally you can select the first column to show user the selection mode. This only have to be done once. The first time you load your form or your datagridview.
// Clear all selected cells or rows in the DGV.
dataGridView1.ClearSelection();
// Make every column not sortable.
for (int i=0; i < dataGridView1.Columns.Count; i++)
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
// Set selection mode to Column.
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
// In case you want the first column selected.
if (dataGridView1.Columns.Count > 0 ) // Check if you have at least one column.
dataGridView1.Columns[0].Selected = true;