在GridView控件+ Asp.net排序
-
23-09-2019 - |
题
我应该怎么做以执行在网格视图排序
请帮助
解决方案
可以实现如以下代码:
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;
}
使用这个代码,你的GridView定义应为:
<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>
其他提示
不知道你是否已经添加事件或没有后面的代码。
您必须为GridView AllowSorting="true"
集,因此,你需要
具有事件处理程序的事件排序
< 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
}
不隶属于 StackOverflow