Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Sunday, 21 September 2014

Delete Records from Gridview using CheckBox in ASP.NET

In this Article, I am going to show you How to Delete Multiple Records from GridView using CheckBox in ASP.NET. This Example is helpful for the situations where User have to delete several records from the database. For Demonstration, I have created a database (named EmployeeDB) in which We have a table named Employee.

Table Schema used in this Example:


CREATE TABLE [dbo].[Employee] (
    [EmpId]     INT          NOT NULL,
    [FirstName] VARCHAR (20) NOT NULL,
    [LastName]  VARCHAR (20) NOT NULL,
    [City]      VARCHAR (20) NOT NULL,
    PRIMARY KEY CLUSTERED ([EmpId] ASC)
);
Let's Begin:
1) Drop GridView Control from the toolbox and set AutoGenerateColumns to false.
2) Add Columns Collection (tag) which manage the collection of Column fields
3) Add TemplateField inside Columns Collection which is used to Display custom content in a data-bound control.
4) Add ItemTemplate in TemplateField which specifies the content to display for the items in a TemplateField.
5) Add CheckBox control inside the ItemTemplate.
6) Inside Columns tag, We have added column field (BoundField) which displays the value of a field in a data source.
7) We have added a Button Control (ID="btnDeleteRecord) for deleting the selected/Checked records.

Default.aspx Code:

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="4">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkDel" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="EmpId" HeaderText="Emp Id" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                <asp:BoundField DataField="City" HeaderText="City" />
            </Columns>
            <HeaderStyle BackColor="#663300" ForeColor="#ffffff" />
            <RowStyle BackColor="#e7ceb6" />
        </asp:GridView>
        <br />
        <asp:Button ID="btnDeleteRecord" runat="server" BackColor="#E7CEB6" Height="32px" OnClick="btnDeleteRecord_Click" Text="Delete" Width="64px" />
        <br />
    </div>
</form>
We have added Javascript(Client side script) so that when user check the CheckBox and click on Delete button, a confirmation pop-up comes on the screen and on accepting the confirmation (By clicking on OK button), click event of server side control fired(btnDeleteRecord_Click) and delete the Checked Record.

<script type="text/javascript">
        function DeleteConfirm() {
            var Ans = confirm("Do you want to Delete Selected Employee Record?");
            if (Ans) {
                return true;
            }
            else {
                return false;
            }
        }
</script>
On Page_Load Event, We disaply the data using showData() method and adding an onclick attribute to Delete button.

Default.aspx.cs Code:

//connection string from web.config file
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            //Displaying the Data
            showData();
            //Adding an Attribute to Server Control(i.e. btnDeleteRecord)
            btnDeleteRecord.Attributes.Add("onclick", "javascript:return DeleteConfirm()");
        }
    }
    //Method for Displaying Data
    protected void showData()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(cs);
        SqlDataAdapter adapt = new SqlDataAdapter("select * from Employee",con);
        con.Open();
        adapt.Fill(dt);
        con.Close();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    //Method for Deleting Record
    protected void DeleteRecord(int empid)
    {
        SqlConnection con = new SqlConnection(cs);
        SqlCommand com = new SqlCommand("delete from Employee where EmpId=@ID",con);
        com.Parameters.AddWithValue("@ID",empid);
        con.Open();
        com.ExecuteNonQuery();
        con.Close();
    }
    protected void btnDeleteRecord_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow grow in GridView1.Rows)
        {
            //Searching CheckBox("chkDel") in an individual row of Grid
            CheckBox chkdel = (CheckBox)grow.FindControl("chkDel");
            //If CheckBox is checked than delete the record with particular empid
            if(chkdel.Checked)
            {
                int empid = Convert.ToInt32(grow.Cells[1].Text);
                DeleteRecord(empid);
            }
        }
        //Displaying the Data in GridView
        showData();
    }
Final Preview:

Hope you like it. Thanks.
[Download Source Code via Google Drive]

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook