问题
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
回答1:
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;
回答2:
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;
回答3:
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;
回答4:
I got this error while starting with WPF using the drag and drop interface and none of the manual coding. Viewing the properties of datagrid would give a way to select items like this:

But trying to change to type to Column Header Select or Column Select would result in the error you mentioned.
So how it was solved was by right-clicking on the grid and go to Edit Columns. Here all the columns and their SortingMode is available to change. Change them all to NotSortable.

来源:https://stackoverflow.com/questions/1987193/datagridview-how-to-select-an-entire-column-and-deselect-everything-else