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]

Sunday, 14 September 2014

Paging in GridView Asp.Net

In this Article, I am going to show you PageIndexChanging Event in GridView. Suppose, We have lot of data in table than, Displaying all the data in GridView without using paging is a Bad Idea. GridView Control provides us paginig feature by which we can break the table data into pages.

Let's Begin:

1) Add GridView control from toolbox and Set AutoGenerateColumns property to false.
2) Set AllowPaging property to True and add OnPageIndexChanging to gridview.
3) I have changed PageSize property of GridView to 5 which sets the number of records to display on a page in a GridView control. Its default value is 10 for a GridView.

Default.aspx Code:


<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" CellPadding="4" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Emp ID" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" />
                <asp:BoundField DataField="City" HeaderText="City" />
            </Columns>
            <HeaderStyle BackColor="#663300" ForeColor="#ffffff"/>
            <RowStyle BackColor="#e7ceb6" />
        </asp:GridView>
    </div>
</form>
The PageIndexChanging event is fired when one of the pager buttons is clicked. We set GridView.PageIndex Property using NewPageIndex property of GridViewPageEventArgs.

Default.aspx.cs Code:

using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    //Connection String from web.config file.
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            DisplayData();
        }
    }
    //Method for Binding Data
    protected void DisplayData()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(cs);
        SqlDataAdapter adapt = new SqlDataAdapter("select * from Record",con);
        con.Open();
        adapt.Fill(dt);
        con.Close();
        if(dt.Rows.Count>0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    //PageIndexChanging occurs on clicking the pager buttons.
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        DisplayData();
    }
}
Final Preview:
Hope you like it. Thanks.
[Download Source via Google Drive]

Watch Video:

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook