ASP.NET通过Checkbox模板删除多个GridView行

时间:2011-11-18 03:27:27

标签: c# asp.net sql

我的应用程序中有一个GirdView表。我在第一列中有一个删除链接按钮和一个复选框。以下是快照:

enter image description here enter image description here

我可以通过点击每行上的删除链接按钮来手动删除每一行。

但是,我想要启用复选框以删除多行。

以下是我的删除链接按钮的代码:

LinkButton lnk = (LinkButton)sender; 
        string stid = lnk.CommandArgument.ToString();
        SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
        string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
        SqlCommand cmd = new SqlCommand(sql,conn);
        conn.Open();
        cmd.ExecuteNonQuery();

以下是我当前删除已检查按钮的代码:

bool atLeastOneRowDeleted = false;
        foreach (GridViewRow row in GridView1.Rows)
        {
            // Access the CheckBox
            CheckBox cb = (CheckBox)row.FindControl("UserSelection");
            if (cb != null && cb.Checked)
            {
                atLeastOneRowDeleted = true;
                // How do I get the value from my Employee column?
                string userID = ???;


           SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
           string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",userID);
           SqlCommand cmd = new SqlCommand(sql,conn);
           conn.Open();
           cmd.ExecuteNonQuery();
            }
        }

我想知道我应该如何在GridView中将用户ID Employee加密到INSERT到我的SQL删除语句?

4 个答案:

答案 0 :(得分:1)

我想你想要

bool atLeastOneRowDeleted = false;
    foreach (GridViewRow row in GridView1.Rows)
    {
        // Access the CheckBox
        CheckBox cb = (CheckBox)row.FindControl("UserSelection");
        if (cb != null && cb.Checked)
        {
            atLeastOneRowDeleted = true;
            //assuming you have the ID column after the controls
            string CusId = (row.Cells[3].Text);


       SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
       string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",userID);
       SqlCommand cmd = new SqlCommand(sql,conn);
       conn.Open();
       cmd.ExecuteNonQuery();
        }
    }

答案 1 :(得分:1)

如果没有看到复选框的代码,我会说复选框的值设置为员工的UserID。然后在提交时将选中的值设置为列表或数组,然后使用delete single方法解析该列表或数组。

答案 2 :(得分:0)

使用'row.Cells [3] .Text'获取列值是一种不好的方法。如果他在中间添加另一列,则索引会发生变化。请改用dataKeys来引用列值。

答案 3 :(得分:0)

这个问题已经得到解答,但是这篇文章显示了使用数据库,Gridview,业务逻辑和DAL的整个流程。

最终预览看起来像这样

enter image description here

您可以找到整个源代码here