当前位置:  开发笔记 > 前端 > 正文

ASP.NET Gridview 中使用checkbox删除的2种方法实例分享

ASP.NETGridview中使用checkbox删除的2种方法实例分享,需要的朋友可以参考一下
方法一:
后台代码:
复制代码 代码如下:

 protected void btn_delete_Click(object sender, EventArgs e)
    {
        for (int i = 0; i         {
            int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value);
            if ((this.GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox).Checked == true)
            {
                Delete(id);
                ClientScript.RegisterStartupScript(GetType(),"提示","");
            }
        }
        this.GridView1.DataBind();
    }//删除
    private void Delete(int id)
    {
        using (SqlConnection conn = new SqlConnection(str))
        {
            conn.Open();
            SqlCommand comm = conn.CreateCommand();
            comm.CommandText = "delete from Notice_Msg where id=@id";
            comm.Parameters.Add(new SqlParameter("@id", id));
            comm.ExecuteNonQuery();
        }
    }

前台代码:
复制代码 代码如下:



另外还得添加一列,让其绑定的字段为id,并且把这一列的visable属性设为false
方法二:
后台:
复制代码 代码如下:

 protected void btn_delete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in this.GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox ckb = row.Cells[2].FindControl("CheckBox1") as CheckBox;
                if (ckb.Checked)
                {
                    using (SqlConnection sqlCnn = new SqlConnection(str))
                    {
                        using (SqlCommand sqlCmm = sqlCnn.CreateCommand())
                        {
                            sqlCmm.CommandText = "delete from Regime_Table where id='" + row.Cells[0].Text + "' ";
                            sqlCnn.Open();
                            int a= sqlCmm.ExecuteNonQuery();
                            if (a>0)
                            {
                                ClientScript.RegisterStartupScript(GetType(),"提示","");
                            }
                            else
                            {
                                ClientScript.RegisterStartupScript(GetType(), "提示", "");
                            }
                            this.DataBind();
                        }
                    }
                }
            }
        }
    }

前台:
复制代码 代码如下:



                  
                  
                  


新增加一列,这一列绑定id字段,并且visable属性不能为false,否则取不出值来。

checkbox全选功能:
复制代码 代码如下:



     
             全选
        

推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有