A personal repository of technical notes. - CSC

Change GridView SortDirection Default

Problem
Need to change the default SortDirection in a GridView for certain columns from ascending to descending.

Solution
Note: This was tested and implemented in ASP.NET 2.0.
  

<asp:GridView DataSourceID="MySqlDataSource" AllowSorting="true" AutoGenerateColumns="false"

ID="MainGridView" runat="server" OnSorting="MainGridView_Sorting">

<Columns>

<asp:BoundField DataField="MyDataField01" SortExpression="MyDataField01" />

<asp:BoundField DataField="MyDataField02" SortExpression="MyDataField02" />

<asp:BoundField DataField="MyDataField03" SortExpression="MyDataField03" />

<asp:BoundField DataField="MyDataField04" SortExpression="MyDataField04" />

<asp:BoundField DataField="MyDataField05" SortExpression="MyDataField05" />

<asp:BoundField DataField="MyDataField06" SortExpression="MyDataField06" />

</Columns>

</asp:GridView>

protected void MainGridView_Sorting(object sender, GridViewSortEventArgs e)

{

// Change default sort order to Descending for certain columns.

switch (e.SortExpression)

{

case "MyDataField01":

case "MyDataField03":

case "MyDataField06":

// Current sort column is different than previous sort column

if (e.SortExpression != MainGridView.SortExpression)

{

e.SortDirection = SortDirection.Descending;

}

break;

default:

break;

}

}

No comments:

Post a Comment

Post a Comment