CodeSnip: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView
page 3 of 6
by Sushila Bowalekar Patel
Feedback
Average Rating: 
Views (Total / Last 10 Days): 35804/ 80

Steps

Step 1 – Create User Interface

Let us drag and drop the GridView control.  We will have the headerTemplate with checkbox to select or deselect all or no records respectively.  In the ItemTemplate we will allow the user to select one or many records when he/she checks the checkbox(s).

To select or deselect the records we will use JavaScript.

Listing 1

<asp:GridView ID="GridView1" datakeyname="Employeeid" runat="server" DataSourceID="Sqldatasource1">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
     <asp:CheckBox ID="CheckAll" onclick="return check_uncheck (this );" runat="server" />
</HeaderTemplate>
<ItemTemplate>
    <asp:Label ID="EmpID" Visible="false" 
    Text='<%# DataBinder.Eval (Container.DataItem, "employeeID") %>'
    runat="server" />
    <asp:CheckBox ID="deleteRec" onclick="return check_uncheck (this );"
                                           runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

On the click of the button we will get the confirmation from the user which is as below:

Listing 2

<asp:Button ID="Button1" runat="server" OnClientClick="return confirmMsg(this.form)"
Text="Button" OnClick="Button1_Click" />

We will use the Employees table from Northwind database.  We will set the SqlDataSource as below:

Listing 3

<asp:SqlDataSource ID="Sqldatasource1" runat="server"
 SelectCommand="Select employeeid,firstname,lastname from Employees"            
ConnectionString="Server=localhost;uid=sa;password=;database=Northwind">
</asp:SqlDataSource>

Step 2 – JavaScript

Let us move to the JavaScript part of the code.

We will see the code for the check_uncheck function given in the Checkbox that is in the <HeaderTemplate> and also the <ItemTemplate>.  Explanation is given inline in the code.

Listing 4

function check_uncheck(Val)
{
  var ValChecked = Val.checked;
  var ValId = Val.id;
  var frm = document.forms[0];
  // Loop through all elements
  for (i = 0; i < frm.length; i++)
  {
    // Look for Header Template's Checkbox
    //As we have not other control other than checkbox we just check following statement
    if (this != null)
    {
      if (ValId.indexOf('CheckAll') !=  - 1)
      {
        // Check if main checkbox is checked,
        // then select or deselect datagrid checkboxes
        if (ValChecked)
          frm.elements[i].checked = true;
        else
          frm.elements[i].checked = false;
      }
      else if (ValId.indexOf('deleteRec') !=  - 1)
      {
        // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
        if (frm.elements[i].checked == false)
          frm.elements[1].checked = false;
      }
    } // if
  } // for// function

Now the Delete confirmation method:

Listing 5

function confirmMsg(frm)
{
  // loop through all elements
  for (i = 0; i < frm.length; i++)
  {
    // Look for our checkboxes only
    if (frm.elements[i].name.indexOf("deleteRec") !=  - 1)
    {
      // If any are checked then confirm alert, otherwise nothing happens
      if (frm.elements[i].checked)
      return confirm('Are you sure you want to delete your selection(s)?')
    }
  }
}

Step 3- Code behind

In the code behind on the click of the button we can code as:

Listing 6

[Visual Basic 2005]

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim gvIDs As String = ""
Dim chkBox As Boolean = False
'Navigate through each row in the GridView for checkbox items
For Each gv As GridViewRow In GridView1.Rows
  Dim deleteChkBxItem As CheckBox = CType(gv.FindControl("deleteRec"), CheckBox)
  If deleteChkBxItem.Checked Then
    chkBox = True
    gvIDs + = CType(gv.FindControl("EmpID"), Label).Text.ToString + ","
  End If
Next
Dim cn As SqlConnection = New SqlConnection(Sqldatasource1.ConnectionString)
If chkBox Then
  Try
  Dim deleteSQL As String = _
 "DELETE from employees WHERE employeeid IN (" + _
 gvIDs.Substring(0, gvIDs.LastIndexOf(",")) + ")"
  Dim cmd As SqlCommand = New SqlCommand( deleteSQL, cn )
  cn.Open()
  cmd.ExecuteNonQuery()
  GridView1.DataBind()
  Catch Err As SqlException
  Response.Write(Err.Message.ToString)
  Finally
  cn.Close()
  End Try
End If
End Sub

 [C#]

protected void Button1_Click(object sender, EventArgs e)
{
  string gvIDs = "";
  bool chkBox = false;
//'Navigate through each row in the GridView for checkbox items
  foreach (GridViewRow gv in GridView1.Rows)
  {
    CheckBox deleteChkBxItem = (CheckBox)gv.FindControl("deleteRec");
    if (deleteChkBxItem.Checked)
    {
      chkBox = true;
// Concatenate GridView items with comma for SQL Delete
      gvIDs += ((Label)gv.FindControl("EmpID")).Text.ToString() + ",";
    }
  }
 
  SqlConnection cn = new SqlConnection(Sqldatasource1.ConnectionString);
  if (chkBox)
  {
// Execute SQL Query only if checkboxes are checked to avoid any error with initial null string
    try
    {
      string deleteSQL = "DELETE from employees WHERE employeeid IN (" +
        gvIDs.Substring(0, gvIDs.LastIndexOf(",")) + ")";
      SqlCommand cmd = new SqlCommand(deleteSQL, cn);
      cn.Open();
      cmd.ExecuteNonQuery();
      GridView1.DataBind();
    }
    catch (SqlException err)
    {
      Response.Write(err.Message.ToString());
    }
    finally
    {
      cn.Close();
    }
 
  }
}

View Entire Article

User Comments

Title: Make invisible not delete   
Name: Harry Hawk
Date: 2007-05-16 8:26:40 AM
Comment:
Hi,

Great, but I am trying to make the row invisible not delete from the database, I'm programming in c#, thanks
Title: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView   
Name: PSteves
Date: 2007-05-04 8:34:09 AM
Comment:
Great article! I've used your technique over and over!

Thanks!
Title: Not so good..   
Name: Pelle
Date: 2007-05-03 10:45:37 AM
Comment:
If you have more checkboxes on the same page - these are also affected.
Title: asp.net   
Name: shivaraya
Date: 2007-04-24 9:16:09 AM
Comment:
this is very nice code.
Title: problem in delete   
Name: virat patel
Date: 2007-03-27 4:38:21 AM
Comment:
thsi code is very help ful for me.
but when i m binding the gridview using dataset and try ur code than i have the problem when i delete the checked record...
it show that no one row is checked in gridview....
help....
Title: ASP.NET   
Name: Gopesh
Date: 2007-03-12 5:39:09 AM
Comment:
Thanks! This article is very useful for all the applications using grids with checkboxes. The great thing is that the code is perfectly working. Thanks Again.
Title: asp.net   
Name: Muhammad Imran Khan
Date: 2007-02-27 4:37:26 AM
Comment:
hahahaha,...... very nice.... good article.....solved my problem...............i like u man .... u is this.......................love you
Title: asp.net   
Name: Roshan Joshi
Date: 2007-02-23 6:41:04 AM
Comment:
First of all thanks sushila .....dear u have provided a great code which is used by every asp.net programmer in developing a project.......great efforts......
Title: check box in gridview   
Name: Kinjal
Date: 2007-02-07 3:53:21 AM
Comment:
gr8 example find that i can used in my application
Title: asp.net   
Name: hyder
Date: 2007-01-23 5:29:02 AM
Comment:
Extermely useful article.
Title: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView   
Name: Felicia
Date: 2006-12-14 12:01:30 AM
Comment:
It works! That is wonderfully awesome!
Title: Sir   
Name: Sem Göksu
Date: 2006-12-12 3:44:43 AM
Comment:
This article is perfect and useful.Thank you !
Title: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView   
Name: ReddySekhar
Date: 2006-12-05 3:01:00 AM
Comment:
This article is really super.
it is very helpfull for deleting and the records in gridview using checkboxes.
thankq sushila
Title: CodeSnip: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView   
Name: pardhu
Date: 2006-11-29 5:48:22 AM
Comment:
thanku sushila
for writing a useful article.
Title: Article Feedback   
Name: secvae
Date: 2006-11-21 2:37:04 AM
Comment:
How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView.
Title: Thank You   
Name: Saranyan
Date: 2006-10-26 7:16:29 AM
Comment:
This task is asked in an interview.I got the solution here.Thanks a Lot.
Title: ASP.NET   
Name: Mr.Devil
Date: 2006-10-19 7:41:37 PM
Comment:
Very useful article, thank you!
:)
Title: How to Select Record(s) Using Checkboxes and Delete on Confirmation in GridView   
Name: mital
Date: 2006-10-19 8:49:15 AM
Comment:
very good
Title: Nice   
Name: Gurpreet S. Gill
Date: 2006-09-30 7:22:57 AM
Comment:
hi "Sushila Bowalekar Patel"....
Gr8 job.
Title: asp.net   
Name: abhijit
Date: 2006-09-26 12:32:51 AM
Comment:
very good

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-28 7:38:17 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search