Selecting, Confirming and Deleting Multiple DataGrid items in ASP.NET
page 1 of 1
Published: 22 Apr 2004
Unedited - Community Contributed
Ever needed to use a DataGrid to select multiple items for deletion, with confirmation, like Hotmail does? This articles demonstrates how in a few simple steps using VB.NET.
by Sameer Lal
Average Rating: 
Views (Total / Last 10 Days): 19409/ 13

Selecting, Confirming and Deleting Multiple Data Grid items

Always wanted to build an easy solution to select multiple items from an ASP.NET DataGrid and delete them all at once like hotmail does?  Well, it is built in just a few simple steps.


To start with, I am assuming that you are using an Access database in the backend and know how to populate DataGrid from database in ASP.NET.  If not, look at my other article for beginners "Basics of Displaying Database Items on Web in ASP.NET" that will be published soon.


Now, to create a selection checkbox in your data grid, first set up your data grid as you would do it normally by dragging and dropping from toolbox in to your webForm1.aspx page. Then right click on data grid and select property builder. Go to column property tab and add a template column to the list of selected columns keeping it on the top of the list. Set the header text value as Select or whatever you wish. Click OK when you are done.






Once you are back on your design page, again right click on data grid and this time you will see another option of edit template column. Click on to edit template column and drag and drop checkbox control into ItemTemplate portion and change its ID to “cbSelect” or whatever name you wish to give it.






When done, right click on it and choose “End Template Editing”. Now, you will see the difference in your data grid, the first column will show up as header “Select” and a checkbox in front of each row.  Now drag and drop a “button” above or below the DataGrid, and add a click event to the button.. You may name the button “Delete Selected”.


Note: My database has key field as SlNo (Serial Number) in tblxyz which is an auto number field and my delete operation will be based on this field. You can have some other field as your key field and you need to modify the codes wherever required.


 Now is the important portion, go to html page mode from design mode and add DataKeyField="SlNo"  after <asp:DataGrid id="DataGrid1" and your code would look something like this:


<body MS_POSITIONING="GridLayout" bgColor="#ccffff">

                        <form id="Form1" method="post" runat="server">

                                    <asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 112px" DataKeyField="SlNo"

                                                runat="server" AutoGenerateColumns="False" Width="464px" Font-Size="X-Small">

                                                <AlternatingItemStyle BackColor="#99FFFF"></AlternatingItemStyle>

                                                <HeaderStyle HorizontalAlign="Center" ForeColor="White" BackColor="DarkBlue"></HeaderStyle>


                                                            <asp:TemplateColumn HeaderText="Select">


                                                                                    <asp:CheckBox id="cbSelected" runat="server"></asp:CheckBox>








Now, again back to design view, drag and drop two oledbCommand controls and type this query in the command text of oleDBCommand1:

DELETE * FROM tblxyz WHERE SlNo =[@SlNo];


In CommandType select Text and in parameters, add a parameter @SlNo



And for oleDBCommand2, type in Command Text as:

SELECT * FROM tblxyz ;



Now, to code behind page, i.e. in my case, it is webform1.aspx.vb, add the following code:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim objItem As DataGridItem


        For Each objItem In DataGrid1.Items


            If objItem.ItemType <> ListItemType.Header And objItem.ItemType <> ListItemType.Footer And objItem.ItemType <> ListItemType.Pager Then

                Dim ChkSelected1 As Boolean

                ChkSelected1 = CType(objItem.Cells(0).FindControl("cbSelected"), CheckBox).Checked


                If ChkSelected1 = True Then


                    Dim SlNo As Integer

                    SlNo = DataGrid1.DataKeys(objItem.ItemIndex).ToString()


OleDbCommand1.Parameters("@SlNo").Value = SlNo





                End If

            End If



        DataGrid1.EditItemIndex = -1



    End Sub


    Sub DataBind1()

        Dim adp As New OleDb.OleDbDataAdapter(OleDbCommand2)

        Dim ds As New DataSet


        DataGrid1.DataSource = ds



    End Sub


Also, if you want to pop up a confirmation message for deletion, like in hotmail, you can add the following codes to page_load sub:


Button3.Attributes("onclick") = "return confirm('Are you sure you _

wish to delete these records?');"



And, that is it. You now have a data grid with hotmail style checkboxes to select multiple records and delete them at once when you click Delete button.






Wait for my next article for beginners “Basics of Displaying Database Items on Web in ASP.Net”

User Comments

Title: Nce Example   
Name: Jaimin Shah
Date: 2011-03-19 3:20:54 AM
It;s good and simple example.... It's really easy and simple.
Title: plz help me out!!   
Name: deekha
Date: 2010-07-30 7:46:28 AM
im trying to delete multiple records using checkboxes in datagrid but it is showing an error ie

Object reference not set to an instance of an object

at line

dgids = CType(i.FindControl("id"), Label).ToString()

here is my sample code

Dim bxschked As Boolean
Dim i As DataGridItem
Dim dgids As String = ""
For Each i In dg3.Items
Dim delchkitm As CheckBox
delchkitm = CType(i.FindControl("chkdel"), CheckBox)
If (delchkitm.Checked) Then
bxschked = True
dgids = CType(i.Cells(0).FindControl("id"), Label).ToString()
End If
Title: Need your help   
Name: Roya
Date: 2009-03-19 5:50:50 PM
Dear Mr Sameer,
How can i add the details of selected row in a new datagrid using c#?

please help me

many thanks

Title: Problem : Object reference not set to an instance of an object.   
Name: Shinji
Date: 2009-02-23 7:42:19 PM
here is the line:

ChkSelected1 = CType(objItem.Cells(0).FindControl("cbSelected"), CheckBox).ToString()

im new hope you can help me
Title: Need you help.   
Name: Mohit
Date: 2008-05-22 7:47:38 AM
I am doing similar delete operation in C#.I have the same conveted in C#.
i am getting error in following lines-Error message is

System.Web.UI.WebControls.BaseDataList.DataKeys denotes a 'property' where a method was expected.

SlNo = DataGrid1.DataKeys(objItem.ItemIndex).ToString() denotes a 'property' where a 'method' was expected.
OleDbCommand1.Parameters("@SlNo").Value = SlNo

Please do the needful.
Title: Just What i needed   
Name: Umair
Date: 2008-04-02 3:58:37 AM
Nice work .. you explain really well :)
Title: About Datagrid   
Name: Suvitha Sadasivam
Date: 2008-03-14 12:34:19 AM
I am not get Datagrid items property. If i typed also i ll get error in that... Do u know how to solve this.. ?
Title: thank u   
Name: sasi
Date: 2008-02-13 5:30:18 PM
its very nice coding
its great help full to me
thanks alot
Title: About Datagrid   
Name: satyanand
Date: 2007-11-14 2:22:03 AM
hi i followed the same for aslo but i could not able to get that the ceck boxes are checked
if chbx.cheked = true then at this statement im not able to get that the check box is cheked id chbx.checked==false...what should i do
pls give me some idea.......
Title: Correction to Post below: C# ASP.NET 2.0 How To   
Name: Michael
Date: 2007-10-16 11:38:04 AM
My bad, thought I had it right, but found a mistake while running it through the debugger. Apparently only half the rows in a datagrid are accessible as ListItemType.Item and the other half are ListItemType.AlternatingItem.

Original (bug) code:
if (item.ItemType.Equals(ListItemType.Item))
{ ....

Fixed code:
if ((item.ItemType.Equals(ListItemType.Item))
{ ....
Title: C# ASP.NET 2.0 How To   
Name: Michael
Date: 2007-10-15 8:30:26 PM
Thanks for the code, it got me pointed in the right direction. For those of you wanting to do this in C# and ASP.NET 2.0, here's a snippet:

foreach (DataGridItem item in photosDG.Items)
if (item.ItemType.Equals(ListItemType.Item))
CheckBox c = (CheckBox)item.FindControl("delPhCB");
if (c.Checked)
catch { }
Title: On Page Load   
Name: Mrugesh
Date: 2007-07-09 2:48:18 AM
Hi this code is working fine
but when the situation is like
i want to display checkbox is checked or not in datagrid while datagrid is loading ie at runtime when data is coming from database...
do u have any code to do that
Thanks heaps
Title: problem   
Name: jyoti
Date: 2007-05-30 5:36:17 AM
i want this code in c# for update.
Title: Delete a record from dataGrid   
Name: venkat
Date: 2007-05-23 6:05:04 AM
Title: request   
Name: puja chaniyara
Date: 2007-05-09 8:50:10 AM
Iam a new student in can you send me the whole code given above in C#language
Title: Problem   
Name: Atul Kumar
Date: 2007-03-08 5:06:43 AM
i want this code in C#. I tried to convert it in C# but encountered an error in this line -

ChkSelected1 = CType(objItem.Cells(0).FindControl("cbSelected"), CheckBox).Checked

it doesn't take 'CheckBox', it says it is a class where a variable is expected and we have used Convert.ToBoolean in place of CType.

The error in this line only..
Boolean chkselected =Convert.ToBoolean(item.Cells[0].FindControl("chk1"),CheckBox);
Title: very useful   
Name: Mohamad
Date: 2007-02-14 6:41:15 PM
Thank you very much for your article. It is really useful.
Title: Validation in Check box   
Name: Pankaj Kumar Sachin
Date: 2007-01-29 7:20:21 AM
Hello Sir!
I have to validate that atleast one checkbox must be selected before pressing the Delete button.If no check box is selected than it shows message that you have to select atleast one .please guide me
Pankaj kumar Sachin from Bihat-Begusarai-Bihar-India
Title: Excellent   
Name: Pankaj Kumar Sachin Begusarai
Date: 2007-01-29 7:15:21 AM
I am new to, and this helps me a lot.this is really a fantastic guide.thanks
Pankaj kumar Sachin from Bihat,Begusarai,Bihar,India
Title: Not Delete records   
Name: Faiz
Date: 2006-12-05 4:13:55 AM

Server Error in '/mfaiz/ImageDemo' Application.

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 70: SqlCommand1.Parameters("@PersonID").Value = PersonID
Line 71:
Line 72: myConnection.Open()
Line 73:
Line 74: SqlCommand1.ExecuteNonQuery()

Please help.

Title: good   
Name: susheel singh
Date: 2006-11-21 1:47:46 PM
good example
Title: excellent   
Name: k.v.subbarao
Date: 2006-10-31 4:10:32 AM
it is good. but links in datagrid to delete
Title: Not deleting the record   
Name: k.s.mathad
Date: 2006-09-23 10:07:11 AM
Dear Sir

in chkselect it showing false after selecting the recrod in check box. Please guide me on this .
Name: Navaid
Date: 2006-08-20 10:16:21 AM

You have done simply a marvellous job man.It has helped me saving my loads n loads of time. Thanks for such a nice and abstract piece of information.

Title: Checkboxes not getting checked   
Name: Savio
Date: 2006-08-16 3:14:48 PM
Actually I faced a similar problem with the checkboxes not being checked. I am actually getting the datagrid in the Sub Page_Load and I have got a function Getdata() which puts the data onto the datagrid. I took care of the problem by just putting the Not IsPostBack over there as follows :

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not IsPostBack Then
End If

End Sub

Hope this helps.
Title: really understandable   
Name: Stalin
Date: 2006-08-08 9:15:32 AM
it really solved my doubt of accessing a datagrid from a control outside a grid.. the coding was neat and understandable.. thanks
Title: Useful Article   
Name: Nafiusul Haque
Date: 2006-07-27 11:37:53 AM
This article is very useful for the beginer of .NET. Such article provides the understanding capability in beginer.
very very thanks to give such valuable info.
Title: not bad   
Name: nikeeta
Date: 2006-07-22 1:05:45 PM
it's helpful for programmer
Title: Excellent   
Name: SamG
Date: 2006-07-14 11:24:18 AM
Write some books - I looked for a good while before stumbling across this - Thanks
Title: C#   
Name: Cash
Date: 2006-07-13 1:37:53 AM
hi i fillowed the same for c# aslo but i could not able to get that the ceck boxes are checked
if(chbx.cheked==true) at this statement im not able to get that the check ox is cheked id chbx.checked==false...what should i do
pls give me some idea.......
Title: Marvellous   
Name: srinivas
Date: 2006-06-12 5:09:47 AM
This is the code, I have been looking since 3 months or more. Finally i captured it and successfully got it.
Appreciating it, I end here
Title: Emraan   
Name: Imran Khan
Date: 2006-06-07 6:42:21 AM
I use ur above method now i have button in datagrid column but when i click it the buttons click event not working. plz guid me what i mdoing wrong.
Title: Fabulous   
Name: Toqeer
Date: 2006-05-25 10:44:33 AM
so nice of u. Its really help full.
Title: help needed   
Name: steelios
Date: 2006-05-06 3:05:28 PM
i generate the datagrid at run time as it is the result of a user doing a search so i have tried to adapt the code to simulate what you are doing here however it is not working at all for me.... its exactly what i want to do but with a dynamic datagrid rather than a static one. can anyone offer any help?????
Title: amman-jordan   
Name: ismail
Date: 2006-04-25 3:30:45 AM
thanks :-
its great but we hope to applity do download this progect
Title: Cool   
Name: Sampath Kumar
Date: 2006-04-24 7:28:26 AM
It's very cool.
Title: Very good   
Name: Yasin
Date: 2006-04-11 4:35:06 AM

Write such details for all other useful controls!!
Title: Selecting, Confirming and Deleting Multiple DataGrid items in ASP.NET   
Name: M.S.Anil Kumar
Date: 2006-04-11 2:34:44 AM
This is one the very good article i have ever seen on this particular Topic.
Title: Superb Example!!!!!   
Name: Kevin
Date: 2006-04-04 1:33:57 PM
Awesome. Almost exactly what I was looking for. Works perfectly. thanks a bunch.
Title: Delete multiple records from datagrid   
Name: nRk
Date: 2006-04-03 1:44:43 AM
This is nice artich with good explanation and Example, this is exactly what i need for which i tried so much time. This article made it simple for me. Thank you.
Title: master   
Name: neil henderson
Date: 2006-04-02 12:19:29 PM
i'am a geek and was having trouble with the checkbox being false, i forgot the postback command what a maroon!!
Title: thank u so much   
Name: gupt
Date: 2006-03-29 12:53:48 AM
what i want is when ever i click the submit iwant to update all the datagrid info to the database.
Title: Software engineer   
Name: vibhu singh
Date: 2006-03-13 7:39:45 AM
good but onlu for begineers
Title: Useful   
Name: Rarichen
Date: 2006-02-14 6:04:50 PM
Thank u for your very useful information.
Title: Getting Error   
Name: Veeraprasad
Date: 2005-12-21 12:41:26 AM
Hai, Code working, i am displaying data using pages. when i select all records in one page getting error " Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount"
Title: how to i add the source code into the "if not ispostback"?   
Name: nick
Date: 2005-09-28 12:40:16 AM
sorry mert, i'm a newbie for, i can't understand that ur code which:
If Not IsPostBack Then
End If
where should i put the code in? can explain clearly to me?or just write the full code for me. i need it ASAP.
thankx for ur help.
regards nick.
Title: Excellent   
Name: chandrkant Garje
Date: 2005-08-23 6:49:23 AM
This artical is very very helpfull for begineer of DataGrid.
Title: ooh lala   
Name: jen
Date: 2005-08-18 8:10:30 AM
oh thanks a lot....i've never seen such a neatly placed and completely written code on net....

and Mert.....Thanks a million...without ur lil piece of tip.....maaan this thing wouldnt have worked
Title: Mr.   
Name: v. bhatia
Date: 2005-07-22 4:14:37 AM
hi there!!! sorry to say if you got 100 records then the connection will be open and close 100 times in this code. is it a good practice.
Title: A useful one   
Name: joe
Date: 2005-06-22 5:27:39 AM
very good
Title: thanx Good   
Name: Joseph
Date: 2005-06-21 5:23:16 AM
Good thanx
Title: HELPPPPPp   
Name: hallu
Date: 2005-06-16 5:26:11 AM
IN CSHARP ???? not in VB :'(
Title: cmert   
Name: Mert
Date: 2005-06-08 10:44:28 PM
I've seen couple of posts here having problems with checkboxes always set to false.
It is happenning because when you hit to submit button your code binds the datagrid again and of course as a result non of the checkboxes are selected. So all of them have the value as FALSE. Here is the solution, place your code between If Not IsPostBack statement as follows;

If Not IsPostBack Then
End If

It should work just fine...

Title: good   
Name: rakesh
Date: 2005-06-01 7:12:55 AM
why dont u write the same code in csharp
Title: hello   
Name: durga prasad
Date: 2005-05-09 10:00:29 AM
it is very good one
Title: Missing code   
Name: Jurelmo
Date: 2005-05-05 9:05:10 PM
Private Sub DataGrid1_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.DeleteCommand

StatusLabel.Text = "Deleted was pressed"

Dim keycolumn As Integer = 1
' gives us the actual data value of the key field of the current row
Dim keyvalue As String = e.Item.Cells(keycolumn).Text

StatusLabel.Text = "Delete was pressed on row " + e.Item.Cells(keycolumn).Text

SqlCommand1.CommandText = "Delete "

Dim DeleteCommand As New SqlCommand("DELETE FROM links WHERE id =" & keyvalue, SqlConnection1)

' execute the command

' rebind the grid
DataGrid1.CurrentPageIndex = 0
DataGrid1.EditItemIndex = -1
Title: Super   
Name: ümit
Date: 2005-04-28 4:25:52 AM
it's really helpfull to me, thank you...
Title: Checkboxes are set to false even after selecting !   
Name: sun
Date: 2005-04-05 8:44:13 AM
Still need help as it is not working.
Title: Thank you   
Name: sophistLady
Date: 2005-03-30 4:36:59 AM
Thank you very much for sharing this piece of code. It is exactly what I needed. Thank u!
Title: Youa are the man   
Name: dg
Date: 2005-02-27 7:22:26 AM
This is one of the most useful things on all net about this problem and it works...
Title: Very Useful   
Name: Prasad
Date: 2005-02-11 1:19:52 AM
very good example for datagrid control in
Title: Excellent   
Date: 2004-11-16 1:19:46 PM
Very thanks for the useful code .This help me a lot . the way of presenting code is very good and easily understandable . Please keep on going to help needy
thanks again
Title: Still need help   
Name: kishori
Date: 2004-11-05 10:10:37 AM
Dear Sir,
This is really a very good code. But I'm facing one problem with this code. The values returned by ckeckboxes are false though they are checked. Please help me.
Title: Good   
Name: jeebu
Date: 2004-10-19 7:28:13 AM
Good code
Title: Not deleting the record   
Name: gireesh
Date: 2004-09-20 2:40:33 AM
Dear Sir

in chkselect it showing false after select the recrod in check box. Please guide me on this .


Private Sub cmddelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmddelete.Click
Dim objitem As DataGridItem
For Each objitem In DataGrid1.Items
'If objitem.ItemType <> ListItemType.Header And objitem.ItemType <> ListItemType.Footer And objitem.ItemType <> ListItemType.Pager Then
Dim chkselect As Boolean
Dim mycode As String
chkselect = CType(objitem.Cells(0).FindControl("chkselect"), CheckBox).Checked
If chkselect = True Then
Dim myconnection As New SqlConnection()
myconnection.ConnectionString = ("Password=gireesh;User ID=gireesh;Initial Catalog=Northwind;Data Source=MAILSERVER")
Dim mydelsql As String
Dim mydelcmd As SqlCommand
mycode = objitem.Cells(1).Text
mydelsql = ("delete from trns_master where trns_code='" + mycode + "'")
mydelcmd = New SqlCommand(mydelsql, myconnection)
End If
End Sub

Private Sub binddata()
Dim myconnection As New SqlConnection()
myconnection.ConnectionString = ("Password=gireesh;User ID=gireesh;Initial Catalog=Northwind;Data Source=MAILSERVER")
Dim mysql As String
Dim myadaptr As SqlDataAdapter
mysql = ("select trns_code from trns_master")
myadaptr = New SqlDataAdapter(mysql, myconnection)
Dim myset As New DataSet()
DataGrid1.DataSource = myset
End Sub
Title: Delete confirmation after selecting check box   
Name: santosh
Date: 2004-09-06 10:31:18 AM
I want delete confirmation box only when i checked the checkbox otherwise it should ask for user to select the check box
Title: Thank you   
Name: Yuriy S
Date: 2004-08-31 1:01:51 PM
Thank you very much for you help. This is exactly what I was looking for. Most of the examples I found on the net, was using C#. I am not familiar with that language. Your example is what I really needed. Thank you.
Title: Very useful   
Name: Eric
Date: 2004-08-05 12:38:41 AM
This is exactly what I needed. I am changing just slightly. I have a program that is to allow a user to assign a specific client to several long distance call records by using the check box method. After they check the records they wish to assign, they then select a client...I then validate the entered client code and update the checked records with the client code.. This for a call allocation problem. thanks for the idea
Title: lending tree, Inc - Lender tech services Summer intern   
Name: Mike D
Date: 2004-07-02 10:48:51 AM
very very very... usefull! A huge help with my internship projects. I appreciate it!
Title: Execellent   
Name: uma
Date: 2004-06-19 1:37:12 AM
It's really excellent, it helped me a lot in learning datagrid

Product Spotlight
Product Spotlight 

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

©Copyright 1998-2024  |  Page Processed at 2024-04-19 3:07:12 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search