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?
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With