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

   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();


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值