Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent sorting of data grid view

I am using a DataGridView on windows form. It displays just two columns. By default when the application is run, if I click on the column headers, the datagridview gets sorted based on that column. However, I want to disable sorting on the grid view completely. I was not able to find a property where I could set sorting = false, or something like that.

Can anyone please tell me how to disable grid view sorting?

Thanks :)

EDIT:

Just figured I could set individual columns as NotSortable (posted answer below). Can it be done at the grid view level, rather than individual columns?

like image 929
SO User Avatar asked Jun 08 '09 11:06

SO User


2 Answers

Okay, found the answer. For each column I need to explicitly specify

this.dgv.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;

So I wrote my own function in a Helper class

/// <summary>
/// Sets the sort mode for the data grid view by setting the sort mode of individual columns
/// </summary>
/// <param name="dgv">Data Grid View</param>
/// <param name="sortMode">Sort node of type DataGridViewColumnSortMode</param>
public static void SetGridViewSortState(DataGridView dgv, DataGridViewColumnSortMode sortMode)
{
    foreach (DataGridViewColumn col in dgv.Columns)
        col.SortMode = sortMode;
}

and wherever, I need to make grid views unsortable, I call it like this:

Helper.SetGridViewSortState(this.dgv, DataGridViewColumnSortMode.NotSortable);
like image 158
SO User Avatar answered Sep 17 '22 07:09

SO User


For i = 0 To DataGridView1.Columns.Count - 1
    DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next i

web gridview has a property AllowSorting which is much easier!

like image 32
ScottE Avatar answered Sep 21 '22 07:09

ScottE