Gridview的初步应用 删除/更新/撤销/编辑/绑定/翻页

来源:互联网 发布:微信积分宝源码 编辑:程序博客网 时间:2024/05/21 10:17
   private SqlConnection gc() //数据库连接
    {
        string str = ConfigurationManager.AppSettings["cs"].ToString();
        SqlConnection mycon = new SqlConnection(str);
        return mycon;
    }


    protected void b()//绑定gridview
    {
        SqlConnection c=gc();
        c.Open();
        string str="select * from tb_StuInfo";
        SqlDataAdapter sda = new SqlDataAdapter(str, c);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        GridView1.DataSource = ds;
       GridView1.DataKeyNames = new string[] { "stuID" };
        GridView1.DataBind();
        c.Close();


    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)//删除
    {
        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string str = "delete from tb_StuInfo where stuID=" + Convert.ToInt32(id);
        SqlConnection c = gc();
        c.Open();
        SqlCommand cmd = new SqlCommand(str, c);
        cmd.ExecuteNonQuery();
        c.Close();
        b();


    }




    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) //翻页
    {
        GridView1.PageIndex = e.NewPageIndex;
        b();
    }










    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) //编辑
    {
        GridView1.EditIndex = e.NewEditIndex;
        b();




    }




    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) //更新
    {
        SqlConnection c = gc();
        c.Open();
        string n = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.Trim();


       Label1.Text= GridView1.Rows[e.RowIndex].Cells[3].Text.ToString();
        string s = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.Trim();
        string h = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.Trim();
        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string sql = "update tb_StuInfo set stuName='" + n + "',stuSex= '" + s + "',stuHobby= '" + h + "' where stuID="+Convert.ToInt32(id);
        SqlCommand cmd = new SqlCommand(sql, c);
        cmd.ExecuteNonQuery();
        c.Close();


        GridView1.EditIndex = -1;
  b();


    
    


    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) //取消
    {
        GridView1.EditIndex = -1;
        b();


    }