Gridview 动态指定字段升序,降序排序
HTML:需要用到事件:onsorting
<asp:GridView ID="MainLists" runat="server" DataKeyNames="WZLBID" CssClass="Grid" AllowSorting="True" OnRowDataBound="MainLists_RowDataBound" AllowPaging="True" OnPageIndexChanging="MainLists_PageIndexChanging" PageSize="15" AutoGenerateColumns="False" OnRowCancelingEdit="MainLists_RowCancelingEdit" OnRowEditing="MainLists_RowEditing" OnRowUpdating="MainLists_RowUpdating" OnRowDeleting="MainLists_RowDeleting" onsorting="MainLists_Sorting"> <FooterStyle CssClass="GridFooter" /> <RowStyle CssClass="Row" /> <Columns> <asp:TemplateField HeaderText="序号" ItemStyle-CssClass="hcenter" ItemStyle-Width="40px" SortExpression="WZLBID" HeaderStyle-ForeColor="White"> <ItemTemplate> <%# Container.DataItemIndex+1 %> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="物资类别名称"> <ItemTemplate> <asp:Label ID="Lab_WZLBMC" runat="server" Text='<%# Eval("WZLBMC") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txt_WZLBMC" Width="120" MaxLength="40" CssClass="inputbox" runat="server" Text='<%# Eval("WZLBMC") %>'></asp:TextBox> </EditItemTemplate> <HeaderStyle HorizontalAlign="Left" Wrap="False" /> <ItemStyle HorizontalAlign="Left" Wrap="False" /> </asp:TemplateField> </Columns> <HeaderStyle CssClass="HeadingCell" /> <AlternatingRowStyle BorderStyle="None" CssClass="AlternatingRow" /> </asp:GridView>
C#:Page_Load
protected void Page_Load(object sender, EventArgs e)
{
MainLists.Attributes["curSortExpression"] = "WZLBID";
MainLists.Attributes["curSortDirection"] = "DESC";
BindData();
}
C#:MainLists_Sorting
protected void MainLists_Sorting(object sender, GridViewSortEventArgs e)
{
if (MainLists.Attributes[e.SortExpression.ToString()] == null)
{
MainLists.Attributes[e.SortExpression.ToString()] = "ASC";
}
else if (MainLists.Attributes[e.SortExpression.ToString()] == "DESC")
{
MainLists.Attributes[e.SortExpression.ToString()] = "ASC";
}
else
{
MainLists.Attributes[e.SortExpression.ToString()] = "DESC";
}
MainLists.EditIndex = -1;
MainLists.Attributes["curSortExpression"] = e.SortExpression.ToString();
MainLists.Attributes["curSortDirection"] = MainLists.Attributes[e.SortExpression.ToString()];
BindData();
}
C#:BindData()
public void BindData()
{
string strwhere = string.Empty;
DataSet ds = bll.GetAllItemByFwzlbid(int.Parse(ViewState["fwzlbid"].ToString()));
if (ds.Tables[0].Rows.Count == 0)
GridViewMsg.InnerText = "无记录";
else
GridViewMsg.InnerText = "共有" + ds.Tables[0].Rows.Count + "条记录";
if (MainLists.Attributes["curSortExpression"] != null)
{
ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", MainLists.Attributes["curSortExpression"], MainLists.Attributes["curSortDirection"]);//这里是排序的地方
}
MainLists.DataSource = ds.Tables[0];
MainLists.DataBind();
}