How to disable sort in DataGridView?

123,751

Solution 1

foreach (DataGridViewColumn column in dataGridView.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

Solution 2

Use LINQ:

Datagridview1.Columns.Cast<DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable);

Solution 3

If you want statically make columns not sortable. You can do this way

  1. Open the EditColumns window of the DataGridView control.
  2. Select the column you want to make not sortable on the left side pane.
  3. In the right side properties pane, select the Sort Mode property and select "Not Sortable" in that.

Solution 4

It's very simple:

foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
    dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}

Solution 5

You can disable it in the ColumnAdded event:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}
Share:
123,751
Gold
Author by

Gold

Updated on October 10, 2020

Comments

  • Gold
    Gold over 3 years

    How can I disable sort in DataGridView? I need to disable the header DataGridView sorting.

  • Nyerguds
    Nyerguds almost 9 years
    Ah, that fixed it. You might want to edit that answer to get the enumeration working right, though ;)
  • Tim Hutchison
    Tim Hutchison almost 7 years
    While this may answer the question, it's always best to include a description/references wherever possible.
  • Bernhard Eriksson
    Bernhard Eriksson about 5 years
    How does this answer differ from the one from @hunter that is five years older?
  • Dôn Kayt
    Dôn Kayt over 3 years
    Or calling CanUserSort = "False" (VS15)