asp.net 2.0下一個標準GRIDVIEW功能的實現(不用datasource控制項)

來源:互聯網
上載者:User

在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")
            {
                ViewState["sortdirection"] = "desc";
            }
            else
            {
                ViewState["sortdirection"] = "asc";
            }
        }
        BindGrid();
    }
很明顯,設定viewsate來儲存每次排序時的順序,上面的相信很容易理解。
     最後,實現編輯功能,因為在aspx頁面中已經設定了OnRowEditing="GridView1_RowEditing",其中GridView1_RowEditing的代碼為
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int empid;
        string fname, lname;
        empid = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
        fname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        lname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;

        SqlConnection cnn = new SqlConnection(@"data source=localhost;initial catalog=northwind;user id=sa;password=123456");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("update employees set firstname=@fname,lastname=@lname where employeeid=@empid", cnn);
        cmd.Parameters.Add(new SqlParameter("@fname",fname));
        cmd.Parameters.Add(new SqlParameter("@lname", lname));
        cmd.Parameters.Add(new SqlParameter("@empid", empid));
        cmd.ExecuteNonQuery();
        cnn.Close();

        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }

  可以看到,上面的代碼和asp.net 1.1版本的其實原理是差不多的。最後,bindgrid()的過程很簡單,為綁定咯
DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter("select * from employees", @"data source=localhost;initial catalog=northwind;user id=sa;password=123456");
        da.Fill(ds,"employees");
        DataView dv = ds.Tables[0].DefaultView;

        if (ViewState["sortexpression"] != null)
        {
            dv.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString();
        }

        GridView1.DataSource=dv;
        GridView1.DataBind();

這裡gridview綁定的是dataview,並且用dv.sort設定了每次排序的順序,也就是說,每次排序後其順序都是保持不變的。
當然最後是page_load事件咯
   protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindGrid();
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.