Você está na página 1de 27

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

Username: HOME

Password: ARTICLES WRITE FOR US ABOUT

Remember me CONTACT

Create new account

I forgot my password

JQUERY-ASP.NET EBOOK

NEWSLETTER E-mail
Browse Articles Article

Name Yes, I want to Subscribe!

Google Custom Search

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

retweet

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.

1 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview. A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview. The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose Relationships. Select all the relationships like FK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we 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 the steps 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 for the 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.

2 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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:Button ID="btnMultipleRowDelete"

3 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command. C# 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("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) { // Retreive the Employee ID int 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.

4 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command'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. Rather than deleting rows one at a time, deleting them in a batch is a good practice. I would encourage you to read Scott Mitchells article for the same.

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

retweet

Share

5 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

You Also Might Like


Using 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 Author


Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

6 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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

Smooth Silverlight Grid The silveright datagrid with a Fluid UI and background retrieval
xceed.com/Grid_Silverlight_Intro

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 AM what 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 AM very nice to see this code but it doesnt looks good for programming ,and the intger specified was to fine but these integer doesnt produce as much 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 the delete 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 1 gets de-selected after moving to page 2, even with EnableViewState=True. TIA. Comment posted by Sri on Thursday, November 22, 2007 9:05 AM Hi, Am doing teh same but "CheckBox checkbox = (CheckBox)row.FindControl("cbRows");" am using teh same stmt but checkbox value is comming 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,

7 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

According to above solution to delete each row,every time we have to go to the database which increases the round trips to the database.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 and send 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 AM I 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 to OverwriteChanges". 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 AM good 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 AM Hi 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 code below, 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());

8 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

} 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 AM This 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 AM Hi 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 AM my 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 AM I 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 PM good article..well is there a more effecient way to delete the multiple selected records in javascript or Ajax to avoid server roundtrips and hence increasing performance.

9 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

Comment posted by Suprotim Agarwal on Saturday, May 03, 2008 7:40 AM It: The VB.NET code has been added Nishant: 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 AM I 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 AM the 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 code for 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 give the users an impressions that the rows were deleted from the GridView. Comment posted by yogesh on Sunday, May 25, 2008 7:35 AM No 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 getting error like Update unable to find TableMapping['ProductDetails'] or DataTable 'ProductDetails'.

using using using using using using using using using using using

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

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

10 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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;

11 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

} 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;

12 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

// } //} // } 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=;Initial Catalog=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 AM Hi, If you do not specify a TableName or a DataTableMapping name when calling the Fill o r Update method of the DataAdapter, the DataAdapter will look for a DataTableMapping named "Table". If that DataTableMapping does not exist, the TableName of the DataTable will be "Table". You can specify 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 AM Well 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 the grid.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

13 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 another table. 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 same http://www.dotnetcurry.com/ShowArticle.aspx?ID=147 Comment posted by Madhu.K.A on Thursday, July 17, 2008 11:09 AM Thank 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 pass the 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 AM Which 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 AM thanks, but you want to delete more than 100 record then it will be take long time. santosh kumar http://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 kumar http://www.operativesystems.com Comment posted by Balaji Ramachandran on Tuesday, August 26, 2008 6:29 AM Thanks 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 of an object

14 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 AM How 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 mine http://www.dotnetcurry.com/ShowArticle.aspx?ID=123 GridView Tips and Tricks http://www.dotnetcurry.com/ShowArticle.aspx?ID=172 Comment posted by Tom George on Saturday, September 13, 2008 2:00 PM Thanks. 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 one colunm(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 AM Hello everyone! i'm very new to asp.net.... I have got a grid that is populated with data from three different sources Now 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 the problem 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)

15 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

{ 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 the database via another grid.... Thanks n regards, Manisha Comment posted by Manisha on Friday, October 03, 2008 3:28 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 the database 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 to apply the changes to the db, call the Update() method of the dataadapter.

16 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 AM i 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 AM I 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 project plz 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 an object".what is the error ,pls help me asap Comment posted by Polson on Thursday, November 20, 2008 7:28 AM Excellenmt 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 AM yes 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) {

17 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 AM How 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 AM Hi, This article is nice. Selecting multiple rows at a time is good to perform. How do we handle this multiple pages . Thanks,

18 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 over here: 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 AM hi 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 when i 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 the PageIndexChanging event. Then retrieve it during the Page_PreRender event. Comment posted by Venkat Keetha on Thursday, March 26, 2009 12:12 AM Hi,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 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 Line Line Line Line 22: 23: 24: 25: 26: { int eid = Convert .ToInt32 (GridView1 .DataKeys[row .RowIndex ].Value ) ; SqlDataSource1 .DeleteParameters ["id"].DefaultValue = eid .ToString() ; SqlDataSource1 .Delete ();

Source File: ....Visual Studio 2008\WebSites\WebSite6\mydbConn.aspx.cs Stack Trace:

Line: 24

[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

19 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

\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 Versio n: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"/>

20 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

</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(); } } }

21 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

But continuously getting the error: Index was out of range. Must be non-negative and less than the size of the collectio n. Parameter name: index Line 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 takes overload 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 page 2) in grid view protected 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(" + Custo merID+ ");"); } 3) use java script function to build a string function 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 Event protected 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 select atleast 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();

22 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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's remain to replace. Comment posted by Jeff Bragin on Tuesday, July 07, 2009 12:39 AM Nikunj 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 delete them 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];

23 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 AM Hi 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 Hai I am facing a problem by deleting multiple records in a gridview by selecting checkboxes like Inbox in gmail account. Comment posted by sujeet on Tuesday, December 15, 2009 5:14 AM hi everyone i 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 list and 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 values are 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 AM Hi, I Am doing the same but "CheckBox checkbox = (CheckBox)row.FindControl("cbRows");" am using the same stmt but checkbox value is comming fales even though its check also. please help me...:-( Comment posted by mukesh mahajan on Wednesday, April 07, 2010 5:33 AM hi i am beginner... how can i get multiple records in gridview from the database

24 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 in this 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 following the 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 AM it sufficient to know about gridview multiple delete you 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 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 Line Line Line Line 16: 17: 18: 19: 20: '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 Then ' Retreive the Employee ID Dim ProductID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value) Line: 18

Source File: J:\RAC\MSDS\main\admin\delete.aspx 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 AM HELLO AM GETTING THIS ERROR< I USE VB.NET

25 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

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 Line Line Line Line 16: 17: 18: 19: 20: '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 Then ' Retreive the Employee ID Dim ProductID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value) Line: 18

Source File: J:\RAC\MSDS\main\admin\delete.aspx 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 AM hey......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 should want 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 AM Server 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 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.

HOME

Source Error: Line 12:

ARTICLES

WRITE FOR US

ABOUT

CONTACT

JQUERY-ASP.NET EBOOK

Disclaimer Terms and Conditions Privacy Policy the //value 'value in the HtmlInputCheckBox's Value property is set asAdvertise of the delete command's parameter. Copyright 2011 dotnetcurry.com (Best Viewed In IE at 1024 * 768 or above)

26 of 27

01/03/2011 11:32

Delete Multiple Rows In A GridView

http://www.dotnetcurry.com/ShowArticle.aspx?ID=66&AspxAutoDetectCookieSupport=1

Line Line Line Line

13: 14: 15: 16:

If checkbox.Checked Then ' Retreive the Employee ID Dim PNo As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value) Line: 14

Source File: C:\Documents and Settings\120224\Desktop\PRACTICE\WebSite2\Default.aspx.vb 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: displayed) Comment:

(Will not be

Insert Cancel

27 of 27

01/03/2011 11:32

Você também pode gostar