如何在GridView中排序

时间:2012-11-15 15:56:11

标签: asp.net sorting gridview

这是我的GV。

<asp:GridView ID="Grid1" runat="server" AutoGenerateColumns="false"
            AllowPaging="True" OnPageIndexChanging="Grid1_PageIndexChanging">
            <Columns>
                <asp:BoundField DataField="One" HeaderText="One" />
                <asp:BoundField DataField="Two" HeaderText="Two" />
                <asp:BoundField DataField="Three" HeaderText="Three" />
            </Columns>
</asp:GridView>

我正在使用存储过程填充GV。

table = PublicClass.Sql_GetTable("usp_GetReportGridView", "NCIU");
Grid1.DataSource = table;
Grid1.DataBind();

如何使用列标题进行排序?

1 个答案:

答案 0 :(得分:2)

首先,您需要启用AllowSorting属性为true。启用后,网格会在每个列的标题中呈现LinkBut​​ton控件。单击该按钮时,将抛出网格的SortCommand事件。您可以在代码中处理此事件。因为DataGrid始终以与数据源中出现的顺序相同的顺序显示数据,所以典型的逻辑对数据源进行排序,然后将数据重新绑定到grid.look代码如下:

//AllowSorting="True"
//OnSorting="GridView2_Sorting"
//SortExpression="name"

protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
  //to check whether to display in ascending order or descending order
  if (e.SortExpression.Trim() == this.SortField)
    this.SortDirection = (this.SortDirection == "D" ? "A" : "D");
  else
    this.SortDirection = "A";
  this.SortField = e.SortExpression;
  TempTable();
}
相关问题