如何在单击按钮时从GridView中删除所选行(使用CheckBox)?

时间:2013-02-21 06:17:02

标签: c# asp.net sql-server web-applications gridview

我有一个GridView,包含从TextBox中提取的多行数据(使用Sessions)。 GridView上应该有一列包含每行上的CheckBoxes,以选择要删除的行。 我在GridView外面有一个Button。单击它,GridView中所有选定的行(使用CheckBox)应从GridView中“删除”。我不想在GridView上使用“删除链接”。

请对下面给出的代码进行必要的更改以实现此功能。

的Default.aspx

<body>
    <form id="form1" runat="server">
    <div>

<asp:Button ID="Button1" runat="server" Text="Add to Grid" OnClick="Button1_Click" />
        <br />

<asp:GridView ID="GridView1" runat="server" DataKeyNames="EmpID" AutoGenerateColumns="false"
    OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
    OnRowDeleting="GridView1_RowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging"
    PageSize="5" AllowPaging="true" OnRowUpdating="GridView1_RowUpdating" Width="800">
    <Columns>
        <asp:TemplateField HeaderText="Employee ID">
            <ItemTemplate>
                <%#Eval("EmpID")%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employee Name">
            <ItemTemplate>
                <%#Eval("EmpName")%>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Salary">
            <ItemTemplate>
                <%#Eval("EmpSalary")%>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#Eval("EmpSalary") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText="Edit">
            <ControlStyle Width="50" />
        </asp:CommandField>
        <asp:TemplateField HeaderText="Delete">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete these records?');">Delete</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>

        **<asp:TemplateField HeaderText="Tick to Delete Rows">
            <ItemTemplate>
                <asp:CheckBox ID="chkDelete" runat="server" Text="Select" />
            </ItemTemplate>
            <HeaderTemplate>
            </HeaderTemplate>
        </asp:TemplateField>**

    </Columns>

</asp:GridView>

</div>

<p style="width: 799px">       
 <asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Delete Checked items" Width="162px" /></p>

</body>

default.aspx.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    DataTable dt1 = new DataTable();
    DataRow dr;
    DataRow dr1;
    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "";
        //lbldbmsg.Text = "";
        if (!Page.IsPostBack)
        {
            dt.Columns.Add("EmpID");
            dt.Columns.Add("EmpName");
            dt.Columns.Add("EmpSalary");
            Session["reptable"] = dt;
            GridData();            
        }
    }

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string EmpID;
        EmpID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        if (Session["reptable"] != null)
        {
            DataTable dt1 = new DataTable();
            dt1.Clear();
            dt1 = Session["reptable"] as DataTable;
            for (int i = 0; i <= dt1.Rows.Count - 1; i++)
            {
                DataRow dr;
                if (dt1.Rows[i][0].ToString() == EmpID)
                {
                    dr = dt1.Rows[i];
                    dt1.Rows[i].Delete();
                    //dt1.Rows.Remove(dr);
                }
            }
            Session.Remove("reptable");
            Session["reptable"] = dt1;
        }
        GridData();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridData();
    }

protected void Button1_Click(object sender, EventArgs e)
    {
        dt = (DataTable)Session["reptable"];
        dr = dt.NewRow();
        dr["EmpID"] = TextBox1.Text;
        dr["EmpName"] = TextBox2.Text;
        dr["EmpSalary"] = TextBox3.Text;
        dt.Rows.Add(dr);
        Session.Remove("reptable");
        Session["reptable"] = dt;
        GridData();
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
    }

protected void Button3_Click(object sender, EventArgs e)
   {

   }
}

3 个答案:

答案 0 :(得分:3)

真的很简单,你所要做的就是:

  1. 循环浏览“删除”按钮OnClick事件
  2. 中的网格视图行
  3. 找到每行中的删除复选框,看看是否勾选了
  4. 实施删除逻辑
  5. 以下是一个示例,我确信您可以根据需要对其进行更改以适应您的方案:

        protected void DeleteClick(object sender,EventArgs e)
        {
            for (int i=0; i < GridView1.Rows.Count;i++)
            {
                CheckBox chkDelete = GridView1.Rows[i].FindControl("chkDelete") as CheckBox;
                if (chkDelete != null && chkDelete.Checked)
                {
                    //Delete the item
                }
            }
        }
    

    <强>更新

    以下是如何删除行

    的示例
    protected void DeleteClick(object sender,EventArgs e)
    {
        DataTable table = (DataTable)Session["reptable"];
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            CheckBox chkDelete = GridView1.Rows[i].FindControl("chkDelete") as CheckBox;
            if (chkDelete != null && chkDelete.Checked)
            {
                var empId = GridView1.DataKeys[i]["EmpID"];
                DataRow dr = table.Select(String.Format("EmpID={0}", empId)).First();
                if (dr != null)
                dr.Delete();
            }
        }
        //Rebind your grid view here to view the changes e.g
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
    

答案 1 :(得分:1)

   foreach (GridViewRow row in GridView1.Rows)
{
    CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
    if (checkbox1.Checked)
    {
        int (primrary key) = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
        SqlCommand cmd = new SqlCommand("delete from student where Primrarykey = @Primrarykey ", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("Primrarykey", SqlDbType.Int).Value = Primrarykey.ToString();
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        cmd.Dispose();
    }
}
grdview_bnd();
}

答案 2 :(得分:0)

您可以在gridview中使用buttonfield而不是checkbox,然后您可以在gridview中添加rowcommand事件示例:
Gridview rowcommand