tags:

views:

825

answers:

4

Hi, 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?

+1  A: 

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);
Rashmi Pandit
A: 

You could always handle the column header click and double click events yourself, and do nothing in them.

GWLlosa
I tried, but it still sorts.
Rashmi Pandit
A: 
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!

ScottE
Yes, eventually thats what I am doing. However, it still is at column level and not grid level.
Rashmi Pandit
+1  A: 

Sorting is, in part, a feature of the data-source. What is the data source in this case? DataTable, perhaps? One option is simply to use a data-source that doesn't support sorting, which is almost all of them. List<T>, BindingList<T> etc - don't provide sorting.

If you must use DataView, you could (I guess) wrap the view with a custom view that re-implements IBindingList (returning false for SupportsSorting), but simply changing the values per column is a lot easier (to the point where it would be crazy to do anything else...)

Marc Gravell