Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Introduction:

In this article I will explain how to delete multiple rows in gridview with checkbox selection and with confirmation message using asp.net.


Description:

I have one gridvew that contains multiple rows with checkboxes now my requirement is to delete rows in gridview based on checkbox selection.


First design the table in database and give name UserInformation
ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
FirstName
varchar(50)
LastName
varchar(50)
Location
varchar(50)
After completion table creation enter some dummy and design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Delete Rows in Gridview with Checkbox</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;  
}
</style>
<script type="text/javascript">
function Confirmationbox() {
var result = confirm('Are you sure you want to delete selected User(s)?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserDetails" runat="server" DataSourceID="objUsers"
DataKeyNames="UserId" CssClass="Gridview" AutoGenerateColumns="false"
HeaderStyle-BackColor="#61A6F8" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="objUsers" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"
DeleteCommand="delete from UserInformation where UserId=@UserId" >
<DeleteParameters>
<asp:Parameter Name="UserId" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />
</form>
</body>
</html>
 
After completion of aspx page write the following code in codebehind


protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Attributes.Add("onclick", "javascript:return Confirmationbox()");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Loop through all the rows in gridview
foreach(GridViewRow gvrow in gvUserDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkdelete");
//Condition to check checkbox selected or not
if(chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
objUsers.DeleteParameters["UserId"].DefaultValue = usrid.ToString();
objUsers.Delete();
}
} 
After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Demo



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

45 comments :

Anonymous said...

Good article. Keep up good work. Good to have sample codes to attach.

Anonymous said...

th example
how to delete multiple rows in gridview with checkbox selection and with confirmation using asp.net
will give an error but i pass all the object refrence in this code
the error is:-

Object reference not set to an instance of an object.

Anonymous said...

please help to solve this error

Suresh Dasari said...

hi,
have you set database connection correctly or not and have you bind your gridview columns with your table columns correctly or not please check it once i tested sample it's working fine.

Anonymous said...

hi i got this type error how to clear...
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Anonymous said...

Object reference not set to an instance of an object. error

Info Tech said...

Thank you so much for this code... It work!!

darshan said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Suresh Dasari said...

@darshan..

That problem is because of data missing your girdiview please check it once whether your are getting data in gridview or not

vinoth said...

thank u for the code.......,

vinoth said...

hello everyone I also got tat "Object reference not set to an instance of an object" error..., the reason is I forgot to add the delete parameter in aspx page.......then worked fine....,

Anonymous said...

sir,in my project i have project on online examination where admin displays questions in grid and admin can delete and view question onclick of grid view view and delete link..but i want to recover deleted question from another grid which can display deleted question..so how can i do that?...sir,plz...give me solution at sabanam.pandey02@yahoo.in

vinoth said...

hello sir in this article the records deleted can't be revived but I want the records to be in database after deletion.......plz help me with a solution......(vin2will@gmail.com).......thank u.......,

suhel said...

hello i want to insert selected item into another data base ,can u guide or send any snippets

Mercy said...

i have error in this line.. show cant covert system.iconvertible

int usrid = Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);

usharaniponnuru40 said...

i have follow this example but an exception is raising as below how can handle this one

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.Data.SqlClient.SqlException: Invalid object name 'UserInformation'.

usharaniponnuru40 said...

i have follow this example but an exception is raising as below how can handle this one

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.Data.SqlClient.SqlException: Invalid object name 'UserInformation'.

Suresh Dasari said...

@usharaniponnuru40..
that problem because of UserInformation table not exists in your database please make sure UserInformation table exists in your database

Anonymous said...

i have two check box in grid one for save and delete.one button save .when i want to delete 2 record i want a popup to appear,only when i check delete checkbox,,so when i have written btn.attribute.add pop up appears for both save and delete

Anonymous said...

very great work. Thanks!

Satish Patil said...

i got this error :-

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Anonymous said...

what if i didn't select any entries?

manohar r said...

sir ,
when i click button inside a gridview data is saving twice in a database.
can u tell why this is happening.

manohar,

Binod kumar said...

thanks so much sir...........may u live long 4 helping we people.............

Binod kumar said...

Sirjiii how to find which CheckBox is checked when we clicked any button.............plz reply sir............

Thanks,
Binod Kumar,Ranchi(Jharkhand)

Suresh Dasari said...

@Binod Kumar...
In this post we are deleting the records based on checkbox selection only. Please check above code to know which checkbox is selected...

Anonymous said...

thanks for example. it is working!

karthick said...

How to data update and delete data in gridview by using gridviewbuttoncolumn event?

Pls help me...

Sri Kumarans School said...

all textboxes are getting unchecked on postback

Sri Kumarans School said...

please help..........

Suresh Dasari said...

@Sri Kumaran...
In postback gridview won't maintain any controls state you need to write custom code to maintain state of checkboxes during postback for that check this article http://www.aspdotnet-suresh.com/2010/04/maintaining-state-of-checkboxes-while.html

Anonymous said...

Thank you suresh.

Ashok said...

How insert the values into footerrow of the gridview in runtime by using sqldatasource with using Templatefield property in .aspx source window only using BoundField property

Tanmoy Barman said...

this code is giving me error:

The name 'objUsers' does not exist in the current context"
how can i rectify this error?

Anonymous said...

Hi,
the grid example is good one..
Can u suggest how can i used the values from multiple selected checkboxes So, when the delete button is pressed, the selected IDs can be passed to a store procedure? Coz i have a procedure which will delete the records for IDs passed in a CSV string.

megha nair said...

Hi, Sir.. This example was very helpful .. Can u please help me in editing and updating ..the seleted row using checkbox..

Anonymous said...

Hello sir,
I got error for:
int usrid = Convert.ToInt32(gvdetails.DataKeys[gvrow.RowIndex].Value);

Error:'System.Web.UI.WebControls.GridView' does not contain a definition for 'RowIndex' and no extension method 'RowIndex' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found (are you missing a using directive or an assembly reference?)
though,I have added all references..
Would you please help me??

Krishh said...

Hello sir .. please same code in VB.net

this is my mail id

gprawin@gmail.com

Anonymous said...

Awsome

Rajiv Rao said...

alternate if range exception triggered

foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkDelete = (CheckBox)row.FindControl("chkDelete");

if (chkDelete != null)
{
if (chkDelete.Checked)
{
string empid = row.Cells[2].Text;
emps = Convert.ToInt16(empid);

}
}
}
}

emp();
}

public void emp()

{
SqlConnection sqld = new SqlConnection(ConfigurationManager.ConnectionStrings["fdbs"].ConnectionString);
SqlCommand cmd = new SqlCommand("Delete from employeedbr where empid=@empid", sqlcon);
SqlParameter spm1 = new SqlParameter("@empid", emps);
cmd.Parameters.Add(spm1);

cmd.ExecuteNonQuery();

GridView1.DataBind();
}

Jitendra Kumar Karna said...

hello suresh.
i want to edit multiple row on one edit button click (gridview contains text box, drop down or what ever control i used in grid view is converted to EditItemTemplete for each row in grid view when i press edit button). please help me as soon as possible...than you in advance....

pankaj said...

sir please start demo i want to see demo also

arun madathil said...

This is very helpful , i am a great fan of u ,

Karthikeyan Palni said...

Hello sir,
I got error for:
int usrid = Convert.ToInt32(gvdetails.DataKeys[gvrow.RowIndex].Value);

Error:'System.Web.UI.WebControls.GridView' does not contain a definition for 'RowIndex' and no extension method 'RowIndex' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found
help out

and also

Chaitanya said...

It is waste for every row delete it is going to database...it is time taking process........ Do all the rows deletion at a time going to database once

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.