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

时间:2022-06-20 08:48:16

I have a GridView containing multiple rows (using Sessions) of data extracted from a TextBox. There should be a column on the GridView containing CheckBoxes on every row to select the rows to be deleted. I have a Button outside the GridView. On click of it, all the selected rows (using CheckBox) from the GridView should be "Deleted" from the GridView. I do not want a "Delete Link" on the GridView.

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

Please make the necessary changes to the code given below to implement this functionality.

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

default.aspx

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

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 个解决方案

#1


3  

It's quite simple really, all you have to do is:

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

  1. Loop through the grid view rows in your Delete buttons OnClick event
  2. 循环遍历删除按钮OnClick事件中的网格视图行
  3. Find the delete check box in each row and see whether it's ticked
  4. 找到每行中的删除复选框,看看它是否已勾选
  5. Implement your delete logic
  6. 实现删除逻辑

Here's an example, I'm sure you can change it as needed to work for your scenario:

这是一个例子,我确信你可以根据需要改变它以适应你的场景:

    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
            }
        }
    }

Update:

更新:

Here's an example of how to delete the rows

这是一个如何删除行的示例

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

#2


2  

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

#3


0  

you can use buttonfield in girdview instead of checkbox and then you can add rowcommand event to your gridview here a example:
Gridview rowcommand

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

#1


3  

It's quite simple really, all you have to do is:

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

  1. Loop through the grid view rows in your Delete buttons OnClick event
  2. 循环遍历删除按钮OnClick事件中的网格视图行
  3. Find the delete check box in each row and see whether it's ticked
  4. 找到每行中的删除复选框,看看它是否已勾选
  5. Implement your delete logic
  6. 实现删除逻辑

Here's an example, I'm sure you can change it as needed to work for your scenario:

这是一个例子,我确信你可以根据需要改变它以适应你的场景:

    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
            }
        }
    }

Update:

更新:

Here's an example of how to delete the rows

这是一个如何删除行的示例

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

#2


2  

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

#3


0  

you can use buttonfield in girdview instead of checkbox and then you can add rowcommand event to your gridview here a example:
Gridview rowcommand

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