Asp.net 如何使asp:GridView可排序?
我有一个Asp.net 如何使asp:GridView可排序?,asp.net,sorting,webforms,Asp.net,Sorting,Webforms,我有一个asp:GridView控件,我已经在该控件上设置了AllowSorting=“True”属性: <asp:GridView ID="gridUsers" runat="server" PageSize="100" ShowHeaderWhenEmpty="True" Width="100%" AllowSorting="True" onrowcreated="gridUsers_RowCreated" onsorting="gridUsers_Sorting">
asp:GridView
控件,我已经在该控件上设置了AllowSorting=“True”
属性:
<asp:GridView ID="gridUsers" runat="server" PageSize="100" ShowHeaderWhenEmpty="True"
Width="100%" AllowSorting="True" onrowcreated="gridUsers_RowCreated"
onsorting="gridUsers_Sorting">
</asp:GridView>
更新:我意识到了描述栏的特殊之处。它是数据库中唯一显示名称正确的列。其余各栏:
现在,我只需要找出棘手的部分;并使列可排序
protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["SortedTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
gridUsers.DataSource = Session["SortTable"];
gridUsers.DataBind();
}
}
改编自此:此代码肯定会帮助您: 在GridView中,将属性AllowSorting=“True”设置为,并在GridView列中给出如下内容
<asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />
这里,考虑“DTS排序”是绑定GRIDVIEW“GV”的DATABATE。
我必须重新设计所有的东西来使用“早期”绑定,而不是“迟”绑定(因此在代码中使用<代码> ASP:BoundField < /代码>)。如果在运行时绑定GridView,它将阻塞。protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["SortedTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
gridUsers.DataSource = Session["SortTable"];
gridUsers.DataBind();
}
}
<asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
gv.DataSource = DTSorting;
gv.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
{
return (DataTable)ViewState["Sorting"];
}
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}