views:

502

answers:

1

Can anyone tell the function to sort the columns of a gridview in c# asp.net.

The gridview is databound to an oracle database. I wanted to click the header of the column to sort the data. i dont know how to refer to the header itself is it using the sender argument of the gridview_sorting method?

Thanks

+2  A: 

In the gridview control set the AllowSorting property to true

<asp:GridView runat="server" ID="gvItems" AllowSorting="true" ...>

In the HeaderTemplate of the column you wish to sort set the SortExpression property to the field the tempate is bound to, if your not using a HeaderTemplate and using a BoundField there should also be a SortExpression property

<asp:TemplateField SortExpression="ItemDescription" HeaderText="Item">...

Implement the OnSorting method

Inside of OnSorting use the second paramerter (GridViewSortEventArgs) to know what the sort expression is and rebind your gridview

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
     string fieldToSortOn = e.SortExpression;

     //implement sort logic on datasource...
}

That should get you a good start

Mcbeev
Great post! I deleted mine, as it was almost an exact copy of this, but I was clearly too slow ;)
Jay S