GridView控件实现CheckBox选中删除数据示例
//GridView设置
asp:TemplateField
/asp:TemplateField
DataFormatString="{0:d}" />
/asp:GridView
//CheckBox设置
Font-Size="9pt" OnCheckedChanged="cbAll_CheckedChanged"
Text="全选/反选" />
Text="部分删除或全部删除" OnClick="btnDeleteMore_Click" onload="btnDeleteMore_Load"
Width="134px" />
OnClick="btnRre_Click" Width="126px" />
//cs页面设置绑定删除信息功能
SqlConnection sqlcon;//加载信息显示数据
string strCon = ConfigurationManager.AppSettings["conStr"];
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GV_DataBind();
}
}//codego.net/tags/15/1/
public void GV_DataBind()
{
string sqlstr = "select * from tb_inf ";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter da = new SqlDataAdapter(sqlstr, sqlcon);
DataSet ds = new DataSet();
sqlcon.Open();
da.Fill(ds, "tb_inf");
sqlcon.Close();
this.GridView1.DataSource = ds;
this.GridView1.DataKeyNames = new string[] { "id" };
this.GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
return;//有数据,不要处理
}
else//显示表头并显示没有数据的提示信息
{
StrHelper.GridViewHeader(GridView1);
}
}
protected void cbAll_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");
if (cbAll.Checked == true)
{
cbox.Checked = true;
}
else
{
cbox.Checked = false;
}
}
}
//选择数据事件
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string id = this.GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
sqlcon = new SqlConnection(strCon);
SqlCommand com = new SqlCommand("select [check] from tb_inf where id='" + id + "'", sqlcon);
sqlcon.Open();
string count = Convert.ToString(com.ExecuteScalar());
if (count == "False")
{
count = "1";
}
else
{
count = "0";
}
com.CommandText = "update tb_inf set [check]=" + count + " where id=" + id;
com.ExecuteNonQuery();
sqlcon.Close();
this.GV_DataBind();
}
//删除数据时弹出对话框
protected void btnDeleteMore_Load(object sender, EventArgs e)
{
((Button)sender).Attributes["onclick"] = "return confirm('您确定要删除吗?')";
}
//删除数据
protected void btnDeleteMore_Click(object sender, EventArgs e)
{
sqlcon = new SqlConnection(strCon);//创建数据库连接
SqlCommand sqlcom;//创建命令对象变量
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)//循环遍历GridView控件每一项
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");//查找嵌套在GridView控件中的单选框
if (cbox.Checked == true)//如果操作为选中状态
{
string strSql = "delete from tb_inf where id=@id";//定义带参数的删除语句
if (sqlcon.State.Equals(ConnectionState.Closed))
sqlcon.Open();//打开数据加连接
sqlcom = new SqlCommand(strSql, sqlcon);//创建执行删除操作的命令对象
SqlParameter prame = new SqlParameter("@id", SqlDbType.Int, 4);//定义参数
sqlcom.Parameters.Add(prame);//添加参数
sqlcom.Parameters["@id"].Value = GridView1.DataKeys[i].Value.ToString();//参数赋值
if (sqlcom.ExecuteNonQuery() > 0)//判断删除是否成功
{
StrHelper.Alert("删除成功!");
}
else
{
StrHelper.Alert("删除失败!");
}
sqlcon.Close();//关闭数据库连接
}
}
GV_DataBind();//重新绑定数据控件
}