日期:2010-10-12  浏览次数:20419 次

在asp.net 2.0下,gridview是十分方便的了,加一个DATASOURCE系列的控件的话,就可以马上和gridview绑定,十分方便。但其实也可以
使用datatable或者dataview的,这个时候就不是用datasource系列控件了。下面讲下如何在asp.net 2.0下,实现gridview控件的翻页,各列排序,
编辑的功能。
    首先,我们读取的是northwind数据库中的employee表。放置一个gridview后,添加几个绑定的列,代码如下
 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None"
            Width="100%" DataKeyNames="EmployeeID" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnSorting="GridView1_Sorting" PageSize="3" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand">
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="employeeid" HeaderText="Employee ID" ReadOnly="True" />
                <asp:BoundField DataField="firstname" HeaderText="First Name" SortExpression="firstname" />
                <asp:BoundField DataField="lastname" HeaderText="Last Name" SortExpression="lastname" />
                <asp:CommandField ShowEditButton="True" />
            </Columns>
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

首先,我们要实现分页,把AllowPaging设置为true,并设置每页的分页条数,最后在codebehind中写入
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
  为了实现每列都可以自动点击排序,可以设置allowsorting=true,然后设置OnSorting="GridView1_Sorting",其中gridview_sorting
代码为
  protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["sortexpression"] = e.SortExpression;

        if (ViewState["sortdirection"] == null)
        {
            ViewState["sortdirection"] = "asc";
        }
        else
        {
            if (ViewState["sortdirection"].ToString() == "asc")
            {