Sorting in GridView + Asp.net
What should I do to perform the sorting开发者_运维百科 in grid view?
Please help
You can implement code like the following:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView1.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
With this code, your GridView definition should read:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="Name" HeaderText="People Names" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="People Ages" SortExpression="Age" />
</Columns>
</asp:GridView>
Not sure if you have already added the event or not in your code behind.
You have AllowSorting="true"
set for the GridView and therefore you need to
have event handler for its Sorting event.
< asp:GridView AllowSorting=true ID="GridView1" runat="server"
OnSorting="GridView1_Sorting" >
...
< /asp:GridView >
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Add your code here for handling
}
精彩评论