Comment posted by
nipun
on Wednesday, August 1, 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 6, 2007 2:41 AM
|
|
what if i dont want to show the ID,for cosmatic things
|
Comment posted by
shoumik
on Tuesday, August 7, 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,
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 3, 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 8, 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());
}
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 9, 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 2, 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 2, 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.
|
Comment posted by
Suprotim Agarwal
on Saturday, May 3, 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 8, 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 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
{
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;
}
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;
// }
//}
// }
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 or 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 1, 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 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 1, 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 4, 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’
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 1, 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 1, 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 3, 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)
{
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 3, 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 3, 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 3, 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.
|
Comment posted by
jignesh kadvani
on Wednesday, October 8, 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 8, 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 9, 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)
{
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 5, 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,
Thani
|
Comment posted by
Suprotim Agarwal
on Friday, February 6, 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 7, 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 8, 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 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\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 />
<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>
<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"/>
</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();
}
}
}
But continuously getting the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Line 32: int id = Convert.ToInt32(GridView1 .DataKeys [row .RowIndex ].Value );
|
Comment posted by
Nikunj Ganatra
on Monday, July 6, 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(" + CustomerID+ ");");
}
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();
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 6, 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 7, 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 9, 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];
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 6, 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 3, 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 7, 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 7, 2010 5:33 AM
|
|
hi
i am beginner... how can i get multiple records in gridview from the database
|
Comment posted by
Michael Giordano
on Wednesday, April 7, 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 9, 2010 7:10 AM
|
|
it sufficient to know about gridview multiple delete
you done good job
|
Comment posted by
avosoft
on Tuesday, May 4, 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 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 Then
Line 19: ' Retreive the Employee ID
Line 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 5, 2010 3:44 AM
|
|
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 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 Then
Line 19: ' Retreive the Employee ID
Line 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 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.
Source Error:
Line 12: 'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
Line 13:
Line 14: If checkbox.Checked Then
Line 15: ' Retreive the Employee ID
Line 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
|
Comment posted by
Pranzo
on Tuesday, March 22, 2011 8:05 AM
|
|
code is perfect but how would i get the same result if im using a aspX Gridview
|
Comment posted by
ENOSH JUSTIN
on Saturday, March 26, 2011 1:56 AM
|
|
thanx for the help
|
Comment posted by
ragini
on Thursday, April 7, 2011 12:08 PM
|
|
i have a problem in my asp.net project.can u help in project
|
Comment posted by
Awon
on Tuesday, July 26, 2011 8:02 AM
|
|
Hello There
I come to know you about About Delete Multiple Records-Checkbox With Select All Button.
I have a url which can help you.
Click Here : http://www.raiseitsolutions.com/foru....php?f=5&t=122
I hope it is enough for you.
Thank You
AWON
|
Comment posted by
mouli
on Friday, September 23, 2011 1:40 AM
|
|
hi this is good article....
while trying this code i cant able to delete the row .
when i try to debug it i found that it shows false for if (checkbox.Checked)
but i made checked in user interface.......
can u please tell me wat is problem over there...
code :
<asp:GridView ID="GridView1" runat="server" Width="484px"
AutoGenerateColumns="False"
DataKeyNames="User_id" RowHeaderColumn="Delete" >
<Columns>
<%-- <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />--%>
<asp:BoundField DataField="User_id" HeaderText="User_id"
SortExpression="User_id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Password" HeaderText="Password"
SortExpression="Password" />
<asp:BoundField DataField="RetypePassword" HeaderText="RetypePassword"
SortExpression="RetypePassword" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:BoundField DataField="TransportName" HeaderText="TransportName"
SortExpression="TransportName" />
<asp:BoundField DataField="DriverName" HeaderText="DriverName"
SortExpression="DriverName" />
<asp:BoundField DataField="Lorry type" HeaderText="Lorry type"
SortExpression="Lorry type" />
<asp:BoundField DataField="LorryNo" HeaderText="LorryNo"
SortExpression="LorryNo" />
<asp:BoundField DataField="MobileNo" HeaderText="MobileNo"
SortExpression="MobileNo" />
<asp:BoundField DataField="LoadName" HeaderText="LoadName"
SortExpression="LoadName" />
<asp:TemplateField >
<HeaderTemplate>
<asp:Label runat="server" Text="Delete"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td></tr>
<tr><td>
<asp:Button ID="Delete" runat="server" Text="Delete" onclick="Delete_Click"/> </td></tr></table>
</div>
</form>
code behind file:
protected void Delete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("myCheckBox");
if (checkbox.Checked)
{
// Retreive the Employee ID
int userid = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
SqlCommand cmd = new SqlCommand("delete from dbo.MBM1 where User_id='" + userid + "'");
//cmd.Parameters.Add("@cat_id", SqlDbType.Int).Value = Convert.ToInt32(autoid);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("WebForm2.aspx");
}
}
}
|
Comment posted by
sumit
on Tuesday, November 15, 2011 4:00 AM
|
|
hello your code is too much helpful. but my button cannot identify the checked checkbox.that is
if (cb.Checked == true)
this condition never been executed though i write the same codes as yours. after clicking on the button my checked checkbox are become unchecked...
Please give me some solution...i am in great problem...
|
Comment posted by
ABHISHEK KUMAR SRIVASTAVA
on Friday, November 25, 2011 12:26 AM
|
|
what is difference b/w c# and asp.net
|
Comment posted by
code ben
on Sunday, December 4, 2011 9:42 PM
|
|
how do you add a row to the gridview using javascript/jquery?
|
Comment posted by
d
on Monday, January 23, 2012 1:17 AM
|
|
sd
|
Comment posted by
abc
on Wednesday, May 2, 2012 3:37 AM
|
|
thanks u!!
|
Comment posted by
arvind
on Friday, June 29, 2012 10:18 AM
|
|
nice one thank u
|
Comment posted by
tina
on Wednesday, August 8, 2012 4:19 AM
|
|
hi good job
|
Comment posted by
Emre
on Wednesday, August 22, 2012 8:10 AM
|
|
People love to share faulty code I guess. Or they are expecting us to fix the small problems.
|
Comment posted by
Vito
on Wednesday, October 9, 2013 3:30 AM
|
|
http://www.kettic.com/winforms_ui/csharp_guide/gridview_row.shtml
|
Comment posted by
sh
on Tuesday, January 28, 2014 4:08 PM
|
|
thank you very much, i wish best wishes for you
|
Comment posted by
krishna
on Tuesday, March 25, 2014 12:47 PM
|
|
kalyan
|
|