Fahhad
Fahhad

Reputation: 85

How can I delete the selected rows (CheckBox used) from the GridView on click of a Button?

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.

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

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)
   {

   }
}

Upvotes: 0

Views: 11522

Answers (3)

user3908915
user3908915

Reputation:

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

Upvotes: 1

Denys Wessels
Denys Wessels

Reputation: 17039

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. Find the delete check box in each row and see whether it's ticked
  3. Implement your delete logic

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

Upvotes: 3

BMW
BMW

Reputation: 630

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

Upvotes: 0

Related Questions