Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView: How to select an entire Column and deselect everything else?

I've been trying to find out how to select all cells under a Column with a 'mouse right click+menu+Select this Column'...

MSDN isn't helping much...

I get this error when I try to change selection mode:

DataGridView control's SelectionMode cannot be set to FullColumnSelect while it has a   column with SortMode set to DataGridViewColumnSortMode.Automatic.

Thanks, Y_Y

like image 322
Y_Y Avatar asked Dec 31 '09 21:12

Y_Y


3 Answers

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;
like image 106
David Avatar answered Nov 18 '22 06:11

David


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;
like image 7
SLaks Avatar answered Nov 18 '22 07:11

SLaks


You need 3 things.

  1. Clear all selected rows and cells.
  2. Remove the sort mode of every column to Not sortable. The default click event is sort, now it will be select.
  3. 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;
like image 3
Tanner Ornelas Avatar answered Nov 18 '22 06:11

Tanner Ornelas