Saturday, 15 July 2017

Delete selected (multiple) rows from GridView using CheckBox with JavaScript confirmation

In this article, I am going to explain you, how to delete multiple records or selected records from GridView control using CheckBox with JavaScript delete confirmation box.

DOWNLOAD SOURCE CODE

Below is the gridview look like when it is binded and alert will be shown when user try to delete the records. Main purpose in this article is to show the delete confirmation box before deleting and delete selected records.

Delete selected records using javascript confirmation box

When a user selects record and click on Delete Selected Records button then a javascript confirmation box will be shown to user whether 'they want to delete select records' and form will be posted to server if click on OK. In this demo, confirmation box is shown whether user selects or doesn't selects any record that means confirmation box will shown to user irrespective of user select or doesn't select any record. I will correct this error in later article.

Delete selected record when checkbox is checked

When user clicks on Delete All button then javascript confirmation box will be shown to user whether 'they want to delete all the records' and all the record will be deleted from current page.

Delete all the records

Data Source

To bind gridview, we need to have some dummy data. Below is the script to create table and insert data into it. Script is attached inside download source code folder.

create table tblStudent
(
Id int primary key identity,
Name varchar(50),
Gender varchar(10),
Marks int,
City varchar(50)
)
go
insert into tblStudent values('Rahul', 'Male', 10, 'Mumbai')
insert into tblStudent values('John','Male', 15,'London')
insert into tblStudent values('Mathew','Male', 20,'Sydney')
insert into tblStudent values('Mary','Female', 25,'Delhi')
insert into tblStudent values('Mithum','Male', 30,'Delhi')
insert into tblStudent values('Sara','Female', 35,'London')
insert into tblStudent values('Rahul','Male', 40,'Mumbai')
insert into tblStudent values('John','Male', 45,'London')
insert into tblStudent values('Mathew','Male', 50,'Sydney')
insert into tblStudent values('Mary','Female', 55,'Delhi')
insert into tblStudent values('Mithum','Male', 60,'Delhi')
insert into tblStudent values('Sara','Female', 65,'London')
insert into tblStudent values('Rahul','Male', 70,'Mumbai')
insert into tblStudent values('John','Male', 75,'London')
insert into tblStudent values('Mathew','Male', 80,'Sydney')
insert into tblStudent values('Mary','Female', 85,'Delhi')
insert into tblStudent values('Mithum','Male', 90,'Delhi')

In Designer File

Create a GridView control with 5 TemplateField. In the first TemplateField, create a LinkButton control inside HeaderTemplate and CheckBox control inside ItemTemplate. On click on LinkButton a JavaScript function DeleteAll will be called which returns true or false accordingly. Create a Button control outside of GridView to delete selected record. On click of delete button, JavaScript function DeleteSelected will be called which also returns true or false accordingly. Below is the complete designer file code with JavaScript functions and to give GridView nicer look, I have used css for header row, footer row and pager row.

Below is the JavaScript and CSS code.

    <script type="text/javascript">
        function DeleteAll() {
            var result = confirm('Are you sure you want to delete all the records?');
            if (result) {
                return true;
            }
            else {
                return false;
            }
        }
        function DeleteSelected() {
            var result = confirm('Are you sure you want to delete selected records?');
            if (result) {
                return true;
            }
            else {
                return false;
            }
        }
    </script>
    <style type="text/css">
        .grdStudentPager {
            background-color: #594c2d;
            color: White;
            padding: 2px;
            margin: 2% auto;
            horizontalalign: left;
        }

            .grdStudentPager a {
                margin: auto 1%;
                border-radius: 50%;
                background-color: #444;
                padding: 5px 10px 5px 10px;
                color: #fff;
                text-decoration: none;
                -o-box-shadow: 1px 1px 1px #111;
                -moz-box-shadow: 1px 1px 1px #111;
                -webkit-box-shadow: 1px 1px 1px #111;
                box-shadow: 1px 1px 1px #111;
            }

                .grdStudentPager a:hover {
                    background-color: #329bd8;
                    color: #fff;
                }

            .grdStudentPager span {
                background-color: #FFFFCC;
                color: Black;
                -o-box-shadow: 1px 1px 1px #111;
                -moz-box-shadow: 1px 1px 1px #111;
                -webkit-box-shadow: 1px 1px 1px #111;
                box-shadow: 1px 1px 1px #111;
                border-radius: 50%;
                padding: 5px 10px 5px 10px;
            }
    </style>

Below is the complete GridView design code.

<div style="margin-top: 25px; margin-left: 250px;">
    <table>
        <tr>
            <td>
                <asp:GridView ID="grdStudent" runat="server" DataKeyNames="Id" CellPadding="5" BackColor="#FFFFCC"
                    AutoGenerateColumns="false" Width="540px" OnPageIndexChanging="grdStudent_PageIndexChanged"
                    AllowPaging="true" PageSize="5" 
                    Style="box-shadow: inset 0 0 10px #000000; -webkit-box-shadow: inset 0 0 10px #000000;
                    -moz-box-shadow: inset 0 0 10px #000000;">
                    <HeaderStyle BackColor="#594c2d" Font-Bold="true" ForeColor="White" />
                    <PagerStyle CssClass="grdStudentPager" />
                    <RowStyle HorizontalAlign="Center" />
                    <Columns>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                <asp:LinkButton ID="btnDeleteAll" runat="server" Text="Delete All" ForeColor="White"
                                    OnClick="btnDeleteAll_Click" OnClientClick="return DeleteAll();">
                                </asp:LinkButton>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Gender">
                            <ItemTemplate>
                                <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Marks">
                            <ItemTemplate>
                                <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="City">
                            <ItemTemplate>
                                <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnDeleteSelected" runat="server" Text="Delete Selected Records"
                    OnClick="btnDeleteSelected_Click" OnClientClick="return DeleteSelected();"
                    Style="color: White; font-size: 12px; font-weight: bold; background-color: #594c2d; 
                    height: 40px; border-radius: 0.5em; padding: 7px; text-transform: uppercase;" />
            </td>
        </tr>
    </table>
</div>

In C# Code-Behind File

Below is the namespace required.

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

Below is the complete C# code to load gridview and to delete record.

// retrieve connection string from web.config file
string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

private void BindGrid()
{
    DataSet ds = null;
    SqlConnection con = null;
    try
    {
        con = new SqlConnection(ConnString);
        SqlCommand cmd = new SqlCommand("select * from tblStudent", con);
        cmd.CommandType = CommandType.Text;
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        ds = new DataSet();
        sda.Fill(ds);

        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            grdStudent.DataSource = ds.Tables[0];
            grdStudent.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            grdStudent.DataSource = ds;
            grdStudent.DataBind();
            grdStudent.Rows[0].Visible = false;
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }
}

protected void grdStudent_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
    try
    {
        grdStudent.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
    try
    {
        foreach (GridViewRow gvrow in grdStudent.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow != null && chkRow.Checked)
            {
                string id = Convert.ToString(grdStudent.DataKeys[gvrow.RowIndex].Values["Id"]);
                if (!string.IsNullOrEmpty(id))
                {
                    DeleteRecord(id);
                }
            }
        }
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

protected void btnDeleteAll_Click(object sender, EventArgs e)
{
    try
    {
        foreach (GridViewRow gvrow in grdStudent.Rows)
        {
            if (gvrow.RowType == DataControlRowType.DataRow)
            {
                string id = Convert.ToString(grdStudent.DataKeys[gvrow.RowIndex].Values["Id"]);
                if (!string.IsNullOrEmpty(id))
                {
                    DeleteRecord(id);
                }
            }
        }
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

private void DeleteRecord(string id)
{
    SqlConnection con = null;
    try
    {
        con = new SqlConnection(ConnString);
        SqlCommand cmd = new SqlCommand("delete from tblStudent where Id=" + Convert.ToInt32(id), con);
        cmd.CommandType = CommandType.Text;
        con.Open();
        int count = cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }
}
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON