27
Username: Password: Remember me Create new account I forgot my password HOME ARTICLES WRITE FOR US ABOUT CONTACT JQUERY-ASP.NET EBOOK Browse Articles Article Google Custom Search retweet retweet Learn how to use jQuery with ASP.NET Controls - 51 Recipes with jQuery and ASP.NET Controls Delete Multiple Rows In A GridView Rating: 167 user(s) have rated this article Posted by: Suprotim Agarwal, on 7/27/2007, in category "ASP.NET" Views: this article has been read 439552 times Abstract: The GridView allows us to delete a single row at a time. In this article, we will explore how to extend this functionality to delete multiple rows at a time. E-mail Name NEWSLETTER Yes, I want to Subscribe! Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1 1 of 27 01/03/2011 11:32

Delete Multiple Rows in a GridView

Embed Size (px)

Citation preview

Page 1: Delete Multiple Rows in a GridView

Username: Password: Remember me Create new account I forgot my password

HOME ARTICLES WRITE FOR US ABOUT CONTACT JQUERY-ASP.NET EBOOK

Browse Articles Article Google Custom Search

retweetretweet

Learn how to use jQuery with ASP.NET Controls - 51 Recipes with jQuery and ASP.NET Controls

Delete Multiple Rows In A GridView

Rating: 167 user(s) have rated this articlePosted by: Suprotim Agarwal, on 7/27/2007, in category "ASP.NET"Views: this article has been read 439552 times

Abstract: The GridView allows us to delete a single row at a time. In this article, we will explore how to extend this functionality to deletemultiple rows at a time.

E-mail

Name

NEWSLETTER

Yes, I want to Subscribe!

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

1 of 27 01/03/2011 11:32

Page 2: Delete Multiple Rows in a GridView

Deleting Multiple Rows in a GridView

If you have used Hotmail or any other similar email client,you might have observed that we have the option ofselecting multiple rows (using the checkbox provided) andperform a set of operations on them. In this article, we willreplicate this scenario for a gridview. A gridview allows us todelete only a single row at a time. We will extend thisfunctionality to select multiple rows and delete all of theselected rows in a single stroke. In this article, I assume thatyou are aware of creating asp.net web applications and haveworked with gridview.

The sample makes use of the Northwind database. We will be pulling data from the Employee table. Forthis sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql ServerManagement Studio, browse to the Northwind database and open the Employee table in design view. Rightclick in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships likeFK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary aswe will get a constraint violation exception if we do not do so.

Once we are through with the task of removing the relationships in the Employee table, let us explore thesteps to create a gridview with functionality to delete multiple rows at a time.

Perform the following steps :

Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.

Step 2: Configure the connection of SqlDataSource to point to the Northwind database. Create queries forthe Select and Delete commands. The resultant code will look similar as given below :

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >

<DeleteParameters><asp:Parameter Name="EmployeeID" />

</DeleteParameters></asp:SqlDataSource>

Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

2 of 27 01/03/2011 11:32

Page 3: Delete Multiple Rows in a GridView

Step 4: To create a checkbox in each row, follow these steps:

1. Create a TemplateField inside the <Columns> to add custom content to each column.2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.

<asp:TemplateField><ItemTemplate>

<asp:CheckBox ID="chkRows" runat="server"/></ItemTemplate>

</asp:TemplateField>

This will add a checkbox to each row in the grid.

Step 5: Add a button control, and rename it to btnMultipleRowDelete.

The resultant markup in the design view will look similar to the code below :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">

<Columns><asp:TemplateField>

<ItemTemplate><asp:CheckBox ID="cbRows" runat="server"/>

</ItemTemplate></asp:TemplateField>

<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"ReadOnly="True" SortExpression="EmployeeID" /><asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName"/><asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />

</Columns></asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >

<DeleteParameters><asp:Parameter Name="EmployeeID" />

</DeleteParameters></asp:SqlDataSource>

<asp:ButtonID="btnMultipleRowDelete"

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

3 of 27 01/03/2011 11:32

Page 4: Delete Multiple Rows in a GridView

OnClick="btnMultipleRowDelete_Click"runat="server"Text="Delete Rows" />

In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loopthrough all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passesthe selected value to the Delete Command.C#

protected void btnMultipleRowDelete_Click(object sender, EventArgs e){

// Looping through all the rows in the GridViewforeach (GridViewRow row in GridView1.Rows)

{CheckBox checkbox = (CheckBox)row.FindControl("cbRows");

//Check if the checkbox is checked.//value in the HtmlInputCheckBox's Value property is set as the //value of thedelete command's parameter.if (checkbox.Checked)

{// Retreive the Employee IDint employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);// Pass the value of the selected Employye ID to the Delete //command.SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue =employeeID.ToString();

SqlDataSource1.Delete(); } } }

VB.NET

Protected Sub btnMultipleRowDelete_Click(ByVal sender As Object, ByVal e As EventArgs)

' Looping through all the rows in the GridView

For Each row As GridViewRow In GridView1.Rows

Dim checkbox As CheckBox = CType(row.FindControl("cbRows"), CheckBox)

'Check if the checkbox is checked.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

4 of 27 01/03/2011 11:32

Page 5: Delete Multiple Rows in a GridView

'value in the HtmlInputCheckBox's Value property is set as the //value of the deletecommand's parameter.

If checkbox.Checked Then

' Retreive the Employee ID

Dim employeeID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)' Pass the value of the selected Employye ID to the Delete //command.

SqlDataSource1.DeleteParameters("EmployeeID").DefaultValue = employeeID.ToString()

SqlDataSource1.Delete()

End If

Next row

End Sub

Run the code, and select a few rows in the grid. ‘Delete Rows’ button, the selected rows get deleted. Ratherthan deleting rows one at a time, deleting them in a batch is a good practice. I would encourage you toread Scott Mitchell’s article for the same.

Conclusion

By default, the gridview provides the functionality to delete a single row at a time. In this article, weexplored how to extend the functionality of the grid view and delete multiple rows. I hope this article wasuseful and I thank you for viewing it.If you liked the article, Subscribe to my RSS Feed or Subscribe Via Email

Subscribe retweetretweet Share

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

5 of 27 01/03/2011 11:32

Page 6: Delete Multiple Rows in a GridView

You Also Might LikeUsing Functions and Helpers in ASP.NET Web Pages - WebMatrix

Using Helper Methods with ASP.NET Web Matrix Beta 3

Configure Secure Socket Layer (SSL) in IIS 7 or IIS 7.5 in Windows 7

Convert Time in Different TimeZones in ASP.NET

ASP.NET WebMatrix Beta 2 - Getting Started

ASP.NET 4.0 Chart control – XML file Binding

About the AuthorSuprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2ZKnowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy onhow to design and develop .NET centric database solutions.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

6 of 27 01/03/2011 11:32

Page 7: Delete Multiple Rows in a GridView

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry.He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

How would you rate this article?

User Feedback

Comment posted by nipun on Wednesday, August 01, 2007 3:28 AM

Man what if i have hundreds of records to be deleted this wud take a hell long time man!!!!

Comment posted by Ahmad Dalqamouny on Monday, August 06, 2007 2:41 AMwhat if i dont want to show the ID,for cosmatic things

Comment posted by shoumik on Tuesday, August 07, 2007 6:00 AM

helpfull article

Comment posted by praveen on Thursday, September 13, 2007 3:58 AMvery nice to see this code but it doesnt looks good for programming ,and the intger specified was to fine but these integer doesnt produce asmuch as babies

Comment posted by Sainey on Monday, October 22, 2007 1:44 PM

Great article. Now, would this work if a user selects, say 3 rows on page 1, moves to page 2 and then selects 3 rows and then clicks on thedelete button? I have used something like this in VS 2003 using a datagrid. Moving from, say page 1 to page 2, everything selected on page 1gets de-selected after moving to page 2, even with EnableViewState=True.TIA.

Comment posted by Sri on Thursday, November 22, 2007 9:05 AMHi,

Am doing teh same but "CheckBox checkbox = (CheckBox)row.FindControl("cbRows");" am using teh same stmt but checkbox value iscomming fales even though its check also.why its comming like this plz give me teh solution.

Comment posted by Madhusudan Dora on Monday, December 10, 2007 6:25 AM

Hi,

Smooth Silverlight GridThe silveright datagrid with a Fluid UI and background retrievalxceed.com/Grid_Silverlight_Intro

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

7 of 27 01/03/2011 11:32

Page 8: Delete Multiple Rows in a GridView

According to above solution to delete each row,every time we have to go to the database which increases the round trips to thedatabase.Instead of that we can use the concept multiple deletion i.e by creating a XML document which will contains the ID's to be deleted andsend it to database(SQL Server 2005) where we can use SP_XML_PREPAREDOCUMENT to make multiple updation.

Thanks Regards,Madhusudan

Comment posted by Suprotim Agarwal on Monday, December 10, 2007 7:28 AM

Hi Madhu, Nice suggestion. You could create an article on this and submit it to the site.

Comment posted by Hung on Friday, December 28, 2007 2:02 AMI do the same way but there is a exception : "You have specified that your delete command compares all values on SqlDataSource'SqlDataSource1', but the dictionary passed in for values is empty. Pass in a valid dictionary for delete or change your mode toOverwriteChanges". Help me!

Comment posted by Suprotim Agarwal on Saturday, December 29, 2007 6:39 AM

Hi Hung, Try setting the SqlDataSource.ConflictDetection to OverwriteChanges.

Comment posted by priyanka on Thursday, January 03, 2008 8:15 AMgood one.but can u suggest me i do i delete aa entries from gridview when it is binded with datatable

Comment posted by U.Janki Rao on Tuesday, January 08, 2008 1:47 AM

Nice Article..!

Comment posted by giteshjoshi on Thursday, January 24, 2008 5:11 AMHi Priyanka, What i understood that u want the code for deleting the records from GridView 1 by 1. If tht's wht ur asking for, please find the codebelow, i hope it can be helpful for u.

//This is RowDeleting event of your gridview.protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e) { //Here you will get the index of the row which you want to delete. int row = e.RowIndex;//Here is the way to retrieve DataKeyName tht u must write in aspx page. (Generally, these are the primary keys only.) string CustomerID = gv1.DataKeys[row]["CustomerID"].ToString();

SqlConnection conn = new SqlConnection(/*Here you write ur connection string. */); //

string query = "delete customers where customerid = '" + CustomerID + "'";//Here goes ur command object. SqlCommand cmd = new SqlCommand(query, conn);

try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Response.Write(ex.Message.ToString());

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

8 of 27 01/03/2011 11:32

Page 9: Delete Multiple Rows in a GridView

} finally { conn.Close(); }

//Again call the function to fill ur grid here. fillGrid(); }

Above you can check using any Boolean or int variable that whether the data is being deleted or not.

--Thanks and Regards,Gitesh

Comment posted by Dushyant on Saturday, February 23, 2008 3:49 AM

Don

Comment posted by subbu on Monday, February 25, 2008 2:30 AMThis is Good ,but this showing 'System.EventArgs' does not contain a definition for 'RowIndex'

Comment posted by Anoop Shrivastava on Sunday, March 09, 2008 8:12 AM

Kindlly suggest me how can I get multiple records from different tables of DB on grid?

Comment posted by Suprotim Agarwal on Monday, March 10, 2008 2:25 AMHi Anoop, Check this link: http://forums.asp.net/t/1132836.aspx

Comment posted by Rohit on Wednesday, April 02, 2008 3:23 AM

i want the code for deleting the records from GridView when check box is checked on gridview plz can u help me

Comment posted by J-Z on Wednesday, April 02, 2008 9:08 AMmy checkboxes always false..... >.<

Comment posted by Gaurav Varshney on Thursday, April 17, 2008 7:36 AM

I have done as given but I am unable to delete row

Comment posted by Kajal on Friday, April 18, 2008 11:37 AMI want to show the data from the database in dataset on the navigate button's click event.How can i do it?I

Comment posted by lt on Monday, April 28, 2008 4:29 PM

what woudl be format of btnMultipleRowDelete function in VB?

Comment posted by Nishant on Wednesday, April 30, 2008 4:30 PMgood article..well is there a more effecient way to delete the multiple selected records in javascript or Ajax to avoid server roundtrips and henceincreasing performance.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

9 of 27 01/03/2011 11:32

Page 10: Delete Multiple Rows in a GridView

Comment posted by Suprotim Agarwal on Saturday, May 03, 2008 7:40 AM

It: The VB.NET code has been addedNishant: You could use asp.net ajax and add the gridview to an update panel

Comment posted by Niteen Patil on Thursday, May 08, 2008 8:30 AMI am realy happy to provide in this type code to solve the user problem.

thank you.....

Comment posted by Hari on Thursday, May 22, 2008 5:44 AM

Hi,CheckBox checkbox = (CheckBox)row.FindControl("cbRows");in the above line checkbox value is showing false after checked also(i mean checkbox in gridview is selected)

Comment posted by lalithashree on Thursday, May 22, 2008 7:44 AMthe code fine. but when i am not using any datasource control how can i delete mutliple rows. i am using data table. can u please give the codefor that

Comment posted by suprotim agarwal on Thursday, May 22, 2008 11:26 AM

Hari: Make sure that the value is still checked when a post back occurs. There could be a possibility that a postback clears out the value

Lalithashree: One approach I can think of is to delete the rows from teh datatable and then bind the datatable back to the GridView. THis will givethe users an impressions that the rows were deleted from the GridView.

Comment posted by yogesh on Sunday, May 25, 2008 7:35 AMNo

Comment posted by lalithashree on Monday, May 26, 2008 3:04 AM

if have put the check box in the template field and for i am using button control to delete the rows. but i am gettingerror like

Update unable to find TableMapping['ProductDetails'] or DataTable 'ProductDetails'.

using System;using System.Data;using System.Data.SqlClient;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Drawing;

public partial class _Default : System.Web.UI.Page{

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

10 of 27 01/03/2011 11:32

Page 11: Delete Multiple Rows in a GridView

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

}

} private DataTable getTable() { SqlConnection conn = new SqlConnection("Integrated Security=SSPI;data source=.;user Id=sa;Password=;Initial Catalog=shopping;"); SqlDataAdapter adap = new SqlDataAdapter("Select * from ProductDetails", conn); DataTable dt = new DataTable(); adap.Fill(dt); return dt; } private void bind() { DataTable dr = getTable(); grd1.DataSource = dr; grd1.DataBind(); }

//public void bindgrid() //{ // SqlConnection con = new SqlConnection("Integrated Security=SSPI;data source=.;user Id=sa;Password=;Initial Catalog=shopping;"); // SqlCommand com = new SqlCommand("select * from ProductDetails", con); //DataSet ds = new DataSet(); // con.Open(); // SqlDataReader reader = com.ExecuteReader(); // grd1.DataSource = reader; // grd1.DataBind(); // con.Close();

//}

protected void grd1_PageIndexChanging(object sender, GridViewPageEventArgs e) { grd1.PageIndex = e.NewPageIndex; bind(); }

private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break;

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

11 of 27 01/03/2011 11:32

Page 12: Delete Multiple Rows in a GridView

} return newSortDirection;

}

protected void grd1_Sorting(object sender, GridViewSortEventArgs e) { bind(); DataTable dataTable = grd1.DataSource as DataTable; if (dataTable != null) { DataView dataView = new DataView(dataTable); dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); grd1.DataSource = dataView; grd1.DataBind(); // bind(); } } protected void grd1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int row = e.RowIndex; string CustomerID = grd1.DataKeys[row]["ProductID"].ToString(); //int ID = (int)GridView1.DataKeys[e.RowIndex].Value; SqlConnection conn = new SqlConnection("Integrated Security=SSPI;data source=.;user Id=sa;Password=;Initial Catalog=shopping;"); string query = "delete productdetails where ProductID = '" + CustomerID + "'"; SqlCommand cmd = new SqlCommand(query, conn);

try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Response.Write(ex.Message.ToString()); } finally { conn.Close(); }

//Again call the function to fill ur grid here. bind(); } // protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e) // { //if (e.Row.RowType = DataControlRowType.DataRow // if (e.Row.RowType == DataControlRowType.DataRow) // {

// if ((e.Row.DataItem("categoryid") < 2)) // {

// e.Row.BackColor = System.Drawing.Drawing.Color.Red;

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

12 of 27 01/03/2011 11:32

Page 13: Delete Multiple Rows in a GridView

// } //} // }

protected void Button1_Click(object sender, EventArgs e) { // e.Row.Cells[i].Value.ToString(); foreach (GridViewRow row in grd1.Rows) { //TextBox2.Text == GridView1.Rows[0].Cells[1].Value.ToString()) string cname = row.Cells[1].Text.ToString(); string del = "delete from productdetails where company=" + cname; CheckBox cb = (CheckBox)row.Cells[3].FindControl("chk"); // CheckBox cb = (CheckBox)row.Cells[3].Controls[1]; if (cb.Checked == true) { SqlConnection conn = new SqlConnection("Integrated Security=SSPI;data source=.;user Id=sa;Password=;InitialCatalog=shopping;"); SqlCommand delsql = new SqlCommand(); delsql.Connection = conn; delsql.CommandText = del; delsql.CommandType = CommandType.Text; SqlDataAdapter da = new SqlDataAdapter(del, conn); da.DeleteCommand = delsql; DataSet ds2 = new DataSet(); da.Update(ds2,"ProductDetails"); }

} }}

Comment posted by lalithashree on Monday, May 26, 2008 3:05 AM

can anybody help me in this

Comment posted by Suprotim Agarwal on Wednesday, May 28, 2008 8:52 AMHi,

If you do not specify a TableName or a DataTableMapping name when calling the Fill or Update method of the DataAdapter, the DataAdapter willlook for a DataTableMapping named "Table". If that DataTableMapping does not exist, the TableName of the DataTable will be "Table". You canspecify a default DataTableMapping by creating a DataTableMapping with the name of "Table"."

Comment posted by Mohd Ali on Tuesday, June 10, 2008 7:57 AM

Nice Article.

Comment posted by Ganesh on Tuesday, July 01, 2008 5:42 AMWell this article is very helpful for deleting the rows which are checked but what if I want to show the records related to the checked rows in thegrid.Well to understand my point let's take a example,suppose there is grid showing User names if I checked four user names among ten and I

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

13 of 27 01/03/2011 11:32

Page 14: Delete Multiple Rows in a GridView

want to show there details like address,email id etc in another grid on another page on a button click.These user details are stored in anothertable.how can I pass multiple checked values to sql server db and get back multiple results???

Comment posted by Suprotim Agarwal on Tuesday, July 01, 2008 7:32 AM

Ganesh: Check another article of mine where you can clues about the samehttp://www.dotnetcurry.com/ShowArticle.aspx?ID=147

Comment posted by Madhu.K.A on Thursday, July 17, 2008 11:09 AMThank you for the good article, i have very usefull, thanks once again, very good

Comment posted by Wissam Bishouty on Tuesday, July 22, 2008 1:37 AM

Concerning the first comment.

You can delete all the checked records with one shot,so you can combine all the checked ids in a stringbuilder seperated by comma and you passthe generetaed stringbuilder as a parameter to the sql and then you can split them by comma and delete one by one on the sql server.

i hope this will help you.

Regards.

Comment posted by Carol on Wednesday, July 23, 2008 1:51 AMWhich Comment are you talking about WissamBishounty

Comment posted by abc on Monday, August 04, 2008 8:33 AM

gtrfdytry

Comment posted by santosh kumar on Thursday, August 21, 2008 3:23 AMthanks,but you want to delete more than 100 record then it will be take long time.

santosh kumarhttp://www.operativesystems.com

Comment posted by santosh kumar on Thursday, August 21, 2008 3:23 AM

thanks,good work done,but you want to delete more than 100 record then it will be take long time.

santosh kumarhttp://www.operativesystems.com

Comment posted by Balaji Ramachandran on Tuesday, August 26, 2008 6:29 AMThanks Buddy

Comment posted by Chandra Shakhar on Thursday, August 28, 2008 2:56 AM

This code is very effective, but when i click checkbox and click delete Button it shows error message ‘Object reference not set to an instance ofan object’

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

14 of 27 01/03/2011 11:32

Page 15: Delete Multiple Rows in a GridView

Kindly help me out.

Thanks & Regards

Comment posted by Priya Joshi on Friday, August 29, 2008 2:53 AM

In the html markup write the delete command & delete parameters.u may have missed it just like me

Comment posted by Akhilesh on Monday, September 01, 2008 1:30 AMHow to change set background color in grid view rows according to given conditions

Comment posted by Suprotim Agarwal on Monday, September 01, 2008 9:34 PM

Akhilesh: Check out these articles of minehttp://www.dotnetcurry.com/ShowArticle.aspx?ID=123

GridView Tips and Trickshttp://www.dotnetcurry.com/ShowArticle.aspx?ID=172

Comment posted by Tom George on Saturday, September 13, 2008 2:00 PMThanks. Very useful.

I have this used in my admin panel for:http://www.findbestwebhosting.com/

Comment posted by Pavani on Tuesday, September 16, 2008 6:19 AM

Hi, i have binded gridview with multiple table.My question is that the data is coming from multiple tables. and i wold like to update only onecolunm(qty) in a table. i have created a (template) Save. My question is how do i catch qty value on button click.

ThankQ,Pavani

Comment posted by Manisha on Friday, October 03, 2008 3:16 AMHello everyone!i'm very new to asp.net....I have got a grid that is populated with data from three different sourcesNow when i insert the data to the grid it is working fine,but when it comes to deleting a row,it is not showing any result....I dont know what theproblem is.......is there any one who can help me.....Here is my code for nserting the data,and for deleting the row...

protected void LinkButton1_Click(object sender, EventArgs e) { if (Session["tbl_item"]==null) { DataColumn dc; dc = new DataColumn("SerialNo", System.Type.GetType("System.String")); dt.Columns.Add(dc); dc = new DataColumn("ItemName", System.Type.GetType("System.String")); dt.Columns.Add(dc); dc = new DataColumn("Quantity",System.Type.GetType("System.String")); dt.Columns.Add(dc); } else {dt = (DataTable) Session["tbl_item"];} if(TextBox4.Visible == false)

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

15 of 27 01/03/2011 11:32

Page 16: Delete Multiple Rows in a GridView

{ string t; if (DropDownList3.Visible == false) { t = "."; } t = DropDownList3.Text; DataRow dr = dt.NewRow(); for (int i = 1; i <= dt.Rows.Count+1; i++) { dr["SerialNo"] = i; } dr["ItemName"] = DropDownList1.Text + " " + DropDownList2.Text + " " + t; dr["Quantity"] = TextBox3.Text; dt.Rows.Add(dr); } if (TextBox4.Visible == true) { DataRow dr1 = dt.NewRow(); dr1["ItemName"] = TextBox4.Text; dr1["Quantity"] = TextBox7.Text; dt.Rows.Add(dr1); } GridView1.DataSource = dt; GridView1.PageSize += 1; GridView1.DataBind();}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int row = e.RowIndex; GridView1.DeleteRow(r); }

Comment posted by Manisha on Friday, October 03, 2008 3:22 AM

One more thing i want to delete the data from the grid only not from the database.........Actually this grid will be used by the user to select some menu items and when they click the submit button the data will be transfered to thedatabase via another grid....Thanks n regards,Manisha

Comment posted by Manisha on Friday, October 03, 2008 3:28 AMOne more thing i want to delete the data from the grid only not from the database.........Actually this grid will be used by the user to select some menu items and when they click the submit button the data will be transfered to thedatabase via another grid....Thanks n regards,Manisha

Comment posted by Suprotim Agarwal on Friday, October 03, 2008 11:25 PM

Manisha: In that case, you should bind the grid with a DataSet and explicitly manipulate only that dataset.

So pull the data using a SQLDataAdapter and populate a dataset. The inmemory dataset can be manipulated by you. When you are ready toapply the changes to the db, call the Update() method of the dataadapter.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

16 of 27 01/03/2011 11:32

Page 17: Delete Multiple Rows in a GridView

Comment posted by jignesh kadvani on Wednesday, October 08, 2008 8:25 AM

above code delete only one selected record. when i check more then one record then it gives error.how to delete multiple checked record from gridview . i am using seprate delete button to delete the record from gridview

Comment posted by gunjan sheth on Wednesday, October 08, 2008 8:28 AMi am facing the same problem as jignesh kadvani facing. could anyone give answer or code for multiple deletion.

Comment posted by Kartik on Thursday, October 09, 2008 6:00 AM

The code works absolutely fine for me. Did you follow the exact steps in the article

Kartik.

Comment posted by sweety on Monday, October 13, 2008 4:26 AMI am new for the asp.net in C#I have to submit my project (STUDENT DATA MANAGEMENT)in two week.So plz what I am do for my projectplz reply early as possible

Comment posted by Nithya on Wednesday, October 15, 2008 3:11 AM

I have done this application-Deleting Multiple Rows in a GridView,but ther is an error like "Object reference not set to an instance of anobject".what is the error ,pls help me asap

Comment posted by Polson on Thursday, November 20, 2008 7:28 AMExcellenmt Article..That made th trick for me...Thanks a Ton.... :)

Comment posted by Unknown on Wednesday, November 26, 2008 2:29 PM

only one word "Awesome"....It saves me..!!!

Comment posted by sanjiv Thakur on Saturday, January 17, 2009 2:03 AMyes this page ..containing very gud stuff.. and in a good mannner..thnx

Comment posted by spwell on Monday, January 26, 2009 3:23 PM

This code works fine. You can alse delete all the rows you selected at one sql command:

protected void btnMultipleRowDelete_Click(object sender, EventArgs e) { string rowIDs = ""; bool chkBox = true;

// Looping through all the rows in the GridView foreach (GridViewRow row in GridView1.Rows) { CheckBox checkbox = (CheckBox)row.FindControl("cbRows");

//Check if the checkbox is checked. //value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter. if (checkbox.Checked) {

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

17 of 27 01/03/2011 11:32

Page 18: Delete Multiple Rows in a GridView

chkBox = true; //get all checked rows in one query string rowIDs += Convert.ToString(GridView1.DataKeys[row.RowIndex].Value) + ",";

} }

SqlConnection cn = new SqlConnection(SqlDataSource1.ConnectionString); if (chkBox) {

try { //get one delete query string string deleteSQL = "DELETE FROM Employees WHERE [EmployeeID] IN (" + rowIDs.Substring(0, rowIDs.LastIndexOf(",")) + ")"; SqlCommand cmd = new SqlCommand(deleteSQL, cn); cn.Open(); cmd.ExecuteNonQuery();

GridView1.DataBind(); } catch (SqlException err) { Response.Write(err.Message.ToString()); } finally { cn.Close(); }

} }

Comment posted by Gautam Dabhade on Thursday, January 29, 2009 8:58 AM

How could i delete record same as u did but using XML?

Comment posted by Gautam Dabhade on Thursday, January 29, 2009 9:04 AMHow could i delete record same as u did but using XML?

Comment posted by spwell on Saturday, January 31, 2009 7:14 AM

Do you mean delete sml nodes at once. Read the following:http://www.aspnettutorials.com/tutorials/database/XML-Csharp.aspx

Comment posted by Thanigainathan.S on Thursday, February 05, 2009 12:35 AMHi,

This article is nice.

Selecting multiple rows at a time is good to perform. How do we handle this multiple pages .

Thanks,

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

18 of 27 01/03/2011 11:32

Page 19: Delete Multiple Rows in a GridView

Thani

Comment posted by Suprotim Agarwal on Friday, February 06, 2009 2:32 AM

Thanigainathan: a simple way is to loop through all the rows in all the pages of a GridView is to access its DataSource. Check out Tip 7 overhere: http://www.dotnetcurry.com/ShowArticle.aspx?ID=172 and try applying the delete logic on it.

Comment posted by venkat on Saturday, March 07, 2009 6:22 AMhi good article.

i have a small doubt. iam using a grid with paging. now in one page im selecting 2 rows and in page 2 im selecting im selecting 3 rows. now wheni want to save the selected rows im only able to save the rows for the selected page not the whole grid.

do u have any idea of this

Comment posted by Suprotim Agarwal on Sunday, March 08, 2009 8:32 AM

Venkat: One way to do it is to create a key-value pair of the selected items, like a hashtable and add it in a session variable during thePageIndexChanging event. Then retrieve it during the Page_PreRender event.

Comment posted by Venkat Keetha on Thursday, March 26, 2009 12:12 AMHi,this is Good article

Comment posted by manish on Tuesday, May 19, 2009 2:55 AM

hi ,i am getting this error while executing the code....

can you help me pls??Server Error in '/WebSite6' 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 moreinformation 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 22: {Line 23: int eid = Convert .ToInt32 (GridView1 .DataKeys[row .RowIndex ].Value ) ;Line 24: SqlDataSource1 .DeleteParameters ["id"].DefaultValue = eid .ToString() ;Line 25: SqlDataSource1 .Delete ();Line 26:

Source File: ....Visual Studio 2008\WebSites\WebSite6\mydbConn.aspx.cs Line: 24

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] mydbConn.muldelFunc(Object sender, EventArgs e) in c:\Documents and Settings\t-managr\My Documents\Visual Studio 2008\WebSites

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

19 of 27 01/03/2011 11:32

Page 20: Delete Multiple Rows in a GridView

\WebSite6\mydbConn.aspx.cs:24 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

--------------------------------------------------------------------------------Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053

Comment posted by Saman Zaidi on Tuesday, May 19, 2009 7:26 AM

<body> <form id="form1" runat="server"> <div> <span style="font-size: 24pt; color: #cc3333"><strong>Inbox<br /> </strong></span> <br /> &nbsp;&nbsp; <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DataStore9.ConnectionString3%>" SelectCommand="SELECT [email], [name], [subject], [content], [Date], [id] FROM [mail]" DeleteCommand="DELETE FROM [mail]WHERE [id] = @id" InsertCommand="INSERT INTO [mail] ([email], [name], [subject], [content], [Date]) VALUES (@email, @name, @subject,@content, @Date)" UpdateCommand="UPDATE [mail] SET [email] = @email, [name] = @name, [subject] = @subject, [content] = @content,[Date] = @Date WHERE [id] = @id"> <DeleteParameters> <asp:Parameter Name="id" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="email" Type="String" /> <asp:Parameter Name="name" Type="String" /> <asp:Parameter Name="subject" Type="String" /> <asp:Parameter Name="content" Type="String" /> <asp:Parameter Name="Date" Type="Object" /> <asp:Parameter Name="id" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="email" Type="String" /> <asp:Parameter Name="name" Type="String" /> <asp:Parameter Name="subject" Type="String" /> <asp:Parameter Name="content" Type="String" /> <asp:Parameter Name="Date" Type="Object" /> </InsertParameters> </asp:SqlDataSource>

</div> &nbsp;&nbsp; <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" CellPadding="4"ForeColor="#333333" GridLines="None" Height="176px" Width="354px"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="chkRows" runat="server"/>

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

20 of 27 01/03/2011 11:32

Page 21: Delete Multiple Rows in a GridView

</ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="id" ReadOnly="True" SortExpression="id" />

<asp:BoundField DataField="name" HeaderText="Sender" SortExpression="name" /> <asp:HyperLinkField DataTextField="subject" HeaderText="Subject" DataNavigateUrlFormatString="~/Tehsildar/readmail.aspx?subject={0}" DataNavigateUrlFields="subject" NavigateUrl="~/Tehsildar/readmail.aspx" Target =main />

<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />

</Columns> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <br /> <br /> <br />

<asp:Button ID="btnMultipleRowDelete" OnClick="btnMultipleRowDelete_Click" runat="server" Text="Delete Rows" BackColor="Maroon" Font-Bold="True" ForeColor="White" />

</form></body>

Code behind:

protected void btnMultipleRowDelete_Click(object sender, EventArgs e) { // Looping through all the rows in the GridView foreach (GridViewRow row in GridView1.Rows) { CheckBox checkbox = (CheckBox)row.FindControl("chkRows");

//Check if the checkbox is checked. //value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter. if (checkbox.Checked) {

int id = Convert.ToInt32(GridView1 .DataKeys [row .RowIndex ].Value ); SqlDataSource1.DeleteParameters["id"].DefaultValue = id.ToString(); SqlDataSource1.Delete(); } }

}

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

21 of 27 01/03/2011 11:32

Page 22: Delete Multiple Rows in a GridView

But continuously getting the error:Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: indexLine 32: int id = Convert.ToInt32(GridView1 .DataKeys [row .RowIndex ].Value );

Comment posted by Nikunj Ganatra on Monday, July 06, 2009 1:15 AM

it's not good apporch,what happen when you had 1000 Record in grid view and user select only five checkbox to delete only five rows. It takesoverload at server side to iterate loop 1000 time for just delete 5 rows.

Insted use Hidden Field and store selected id as a string in client side.

for that follow this step,1) Add hidden field in your page2) in grid viewprotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){if (e.Row.RowType == DataControlRowType.DataRow) { DataRowView rvCustomer = (DataRowView)e.Row.DataItem; int CustomerID= int.Parse(rvCustomer.Row["CustomerID"].ToString());

CheckBox cbRows= (CheckBox)e.Row.FindControl("cbRows"); chkRemoveWeek.Attributes.Add("onclick", "GetSelectedCustomerID(" + CustomerID+ ");");

}

3) use java script function to build a stringfunction GetSelectedWeekID(CustomerID) { var strCustomer = document.getElementById('<%=hdnSelectedCustomer.ClientID %>').value; if(strCustomer=="") strCustomer= CustomerID + ";"; else strCustomer= strCustomer + CustomerID + ";";

document.getElementById('<%=hdnSelectedCustomer.ClientID %>').value=strWeeks; }

4)now Call Remove/Delete selected Customer Eventprotected void btnMultipleRowDelete_Click(object sender, EventArgs e) { Array strCustomerID = hdnSelectedCustomer.Value.Split(';');

if (strCustomerID.Length == 1) ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "", "<script language='Javascript' defer='true'>alert('Please selectatleast one week which you want to remove.'); </script>", false); else { for (int i = 0; i < strCustomerID.Length - 1; i++) { int id = int.Parse(strCustomerID.GetValue(i).ToString()); try { SqlDataSource1.DeleteParameters["id"].DefaultValue = id.ToString();

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

22 of 27 01/03/2011 11:32

Page 23: Delete Multiple Rows in a GridView

SqlDataSource1.Delete();

lblMessage.Text = Message.DeleteRecord; } catch (System.Data.SqlClient.SqlException ex) { if (ex.Message.ToLower().Contains("conflicted with the REFERENCE constraint".ToLower())) { lblMessage.Text = Message.CantDelete; } } catch (Exception ex) { throw ex; } lblMessage.Visible = true; } BindGrid(); //Bind grid with new data hdnSelectedWeek.Value = ""; //clear the hidden field value } }

Comment posted by Nikunj Ganatra on Monday, July 06, 2009 1:27 AM

In above code whereever you find "Week", just replace by "Customer"...because I had posted the code what I m using , so in some place it'sremain to replace.

Comment posted by Jeff Bragin on Tuesday, July 07, 2009 12:39 AMNikunj Ganatra:

indeed it is a very good approach, i like it. but why bother to split out the ids and delete it one by one, why not use spwell approach to deletethem in one shot?

Comment posted by dhaval patel on Thursday, July 09, 2009 6:14 AM

'System.Web.UI.WebControls.GridView' does not contain a definition for 'rows'

protected void OnRowCommand(object sender, GridViewCommandEventArgs e) { int index = Convert.ToInt32(e.CommandArgument); GridViewRow gvrow = GridView1.rows[index]; } protected void Button1_Click(object sender, EventArgs e) { GridViewRow gvrow = (GridViewRow)(sender as Control).Parent.Parent; int index = gvrow.RowIndex;

Button btn = (Button)sender; string CommandName = btn.CommandName; string[] CommandArgument = btn.CommandArgument.Split(','); string CommandArgument1 = CommandArgument[0]; string CommandArgument2 = CommandArgument[1];

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

23 of 27 01/03/2011 11:32

Page 24: Delete Multiple Rows in a GridView

string CommandArgument3 = CommandArgument[2]; string CommandArgument4 = CommandArgument[3]; string CommandArgument5 = CommandArgument[4];

Comment posted by Nikunj Ganatra on Friday, July 10, 2009 9:52 AM

Hi, Dhaval Patel...can u plz specify what operation do you want to perform?

for (int i =0; i < gvWeekly.Rows.Count; i++) {

GridViewRow row = gvWeekly.Rows[i]; }

for temp solution use this code to find all the rows in grid view.

Comment posted by Shaane Punjab on Friday, October 30, 2009 5:37 AMHi All,

Nice Article and well presented. The content is very clear and i wish all the best to the author for her future articles.

Comment posted by vivek on Friday, November 06, 2009 4:05 AM

HaiI am facing a problem by deleting multiple records in a gridview by selecting checkboxeslike Inbox in gmail account.

Comment posted by sujeet on Tuesday, December 15, 2009 5:14 AMhi everyonei am got grid and i want to three diff. coloum to bound and in header field i want to drop down list when i drop any list and select any item on listand after selecting we press delete button the item deleted in database and show to grid.....can anyone help me...thanks!..in advance....

Comment posted by rahul on Wednesday, February 03, 2010 4:49 PM

hi, i am beginner in .net,i need the c# code to delete a row in gridview(windowsform)without connecting through any database.The data valuesare being added through another popup window please give me a soltion i am getting struct in it

Comment posted by Anamika on Wednesday, April 07, 2010 3:37 AMHi,

I Am doing the same but "CheckBox checkbox = (CheckBox)row.FindControl("cbRows");" am using the same stmt but checkbox value iscomming fales even though its check also. please help me...:-(

Comment posted by mukesh mahajan on Wednesday, April 07, 2010 5:33 AM

hii am beginner... how can i get multiple records in gridview from the database

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

24 of 27 01/03/2011 11:32

Page 25: Delete Multiple Rows in a GridView

Comment posted by Michael Giordano on Wednesday, April 07, 2010 4:46 PM

Excellent Article!! Thank you. Caught two small mishaps that might helps some others.

One The Gridview much Contain this:<DeleteParameters><asp:Parameter Name="ID" Type="Int32" /></DeleteParameters>

And second, their is small discrepency with the CheckBox ID, In Step 2 it is listed as chkRows and in Step 5 it is listed as cbRows. Your code inthis section will have to reference the correct ID you have, in this case the cbRows ID. Took me a few minutes as I actually typed out followingthe step by step instructions and glossed over the ID in my code.

Excellent article.

Comment posted by sanjay on Friday, April 09, 2010 7:10 AMit sufficient to know about gridview multiple deleteyou done good job

Comment posted by avosoft on Tuesday, May 04, 2010 11:08 PM

HELLO AM GETTING THIS ERROR< I USE VB.NET

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 moreinformation 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 16: 'Check if the checkbox is checked.Line 17: 'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.Line 18: If checkbox.Checked ThenLine 19: ' Retreive the Employee IDLine 20: Dim ProductID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

Source File: J:\RAC\MSDS\main\admin\delete.aspx Line: 18

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] ASP.admin_delete_aspx.btnMultipleRowDelete_Click(Object sender, EventArgs e) in J:\RAC\MSDS\main\admin\delete.aspx:18 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4921

Comment posted by avosoft on Wednesday, May 05, 2010 3:44 AMHELLO AM GETTING THIS ERROR< I USE VB.NET

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

25 of 27 01/03/2011 11:32

Page 26: Delete Multiple Rows in a GridView

HOME ARTICLES WRITE FOR US ABOUT CONTACT JQUERY-ASP.NET EBOOKDisclaimer Terms and Conditions Privacy Policy Advertise

Copyright © 2011 dotnetcurry.com (Best Viewed In IE at 1024 * 768 or above)

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 moreinformation 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 16: 'Check if the checkbox is checked.Line 17: 'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.Line 18: If checkbox.Checked ThenLine 19: ' Retreive the Employee IDLine 20: Dim ProductID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

Source File: J:\RAC\MSDS\main\admin\delete.aspx Line: 18

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] ASP.admin_delete_aspx.btnMultipleRowDelete_Click(Object sender, EventArgs e) in J:\RAC\MSDS\main\admin\delete.aspx:18 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4921

Comment posted by kazzar sawssen on Monday, May 17, 2010 1:00 PM

comment fait le coce de boutton supprimer au asp.net acces

Comment posted by sonali singh on Monday, October 25, 2010 1:06 AMhey......can u plz tell me the right method of deleting multiple rows...from a grid view if we are not connected to the data base...

Comment posted by A.Sundaravelan on Monday, February 14, 2011 5:49 AM

I want to display the content of the gridviewtable in textbox ,by using checkbox in the gridview i should select the row of data,which i shouldwant to display on textbox.And then i need to edit that textbox content..

Comment posted by S R Chowdhuy on Tuesday, February 15, 2011 2:45 AMServer Error in '/WebSite2' 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 moreinformation 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 12: 'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

26 of 27 01/03/2011 11:32

Page 27: Delete Multiple Rows in a GridView

Line 13:Line 14: If checkbox.Checked ThenLine 15: ' Retreive the Employee IDLine 16: Dim PNo As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

Source File: C:\Documents and Settings\120224\Desktop\PRACTICE\WebSite2\Default.aspx.vb Line: 14

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] _Default.btnMultipleRowDelete_Click(Object sender, EventArgs e) in C:\Documents and Settings\120224\Desktop\PRACTICE\WebSite2\Default.aspx.vb:14 System.EventHandler.Invoke(Object sender, EventArgs e) +0 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919

Comment posted by TAUSIF on Wednesday, February 23, 2011 12:25 AM

HELPFULL ARTICLES

Post your comment

Name:

E-mail: (Will not bedisplayed)

Comment:

Insert Cancel

Delete Multiple Rows In A GridView http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

27 of 27 01/03/2011 11:32