GridView排序

该例子以MyBookShop项目为基础,给图书列表增加一个排序功能。效果如下:



第一步:在页面上拖入一个GridView控件,绑定其数据源;

GridView保留Id,Title,Author,PublishDate这四个字段,ObjectDataSource数据源控件的TypeName属性为BLL.BookManager,SelectMethod属性为GetAllBooks()。源码如下:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetAllBooks"
            TypeName="MyBookShop.BLL.BookManager"></asp:ObjectDataSource>
第二步:您观察到GridView中每个字段都有一个SortExpression属性吗?这个属性就是用来进行排序的,当你启动排序后点击标头就会将这个属性值传递给ObjectDataSource控件,我们只需要在ObjectDataSource控件中添加一个属性接受这个值就可以了。所以在ObjectDataSource控件中添加:
SortParameterName="SortExpression"

第三步:现在你可以浏览一下,看看发生什么情况。



现在你能猜到排序是怎么工作的吧,即把SortExpression的属性值作为一个参数传递给Bll层中的GetAllBooks方法。显然,我们现在需要在Bll层和DAL层中增加一个带参数的GetAllBooks方法,而且参数名称只能是SortExpression。 首先是DAL层:

public static IList<Book> GetAllBooks(string SortExpression)
        {
            string sql = "select * from Books";
            if (SortExpression != "")
            {
                sql += " order by " + SortExpression;
            }

            return GetPartialBooksBySql(sql);
        }

   BLL层:

public static IList<Book> GetAllBooks(string SortExpression)
        {
            return BookService.GetAllBooks(SortExpression);
        }
第四步:启动分页和排序



第五步:我们还可以进行自定义排序。添加一个DropDownList控件,将4个字段值添加到DropDownList控件的列表中,启动AutoPostBack。代码:

       <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
            <asp:ListItem>Id</asp:ListItem>
            <asp:ListItem>Title</asp:ListItem>
            <asp:ListItem>Author</asp:ListItem>
            <asp:ListItem>PublishDate</asp:ListItem>
        </asp:DropDownList>


最后添加DropDownList控件的SelectedIndexChanged事件代码:

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.Sort(DropDownList1.SelectedValue, SortDirection.Ascending);
    }
原文地址:https://www.cnblogs.com/lds85930/p/1362318.html