Introduction:
In this article I will explain how to delete multiple rows in gridview with checkbox selection and with confirmation message using asp.net.
First design the table in database and give name UserInformation
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.
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. |
|||
|
|||
46 comments :
Good article. Keep up good work. Good to have sample codes to attach.
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.
please help to solve this error
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.
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
Object reference not set to an instance of an object. error
Thank you so much for this code... It work!!
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
@darshan..
That problem is because of data missing your girdiview please check it once whether your are getting data in gridview or not
thank u for the code.......,
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....,
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
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.......,
hello i want to insert selected item into another data base ,can u guide or send any snippets
i have error in this line.. show cant covert system.iconvertible
int usrid = Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
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'.
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..
that problem because of UserInformation table not exists in your database please make sure UserInformation table exists in your database
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
very great work. Thanks!
i got this error :-
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
what if i didn't select any entries?
sir ,
when i click button inside a gridview data is saving twice in a database.
can u tell why this is happening.
manohar,
thanks so much sir...........may u live long 4 helping we people.............
Sirjiii how to find which CheckBox is checked when we clicked any button.............plz reply sir............
Thanks,
Binod Kumar,Ranchi(Jharkhand)
@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...
thanks for example. it is working!
How to data update and delete data in gridview by using gridviewbuttoncolumn event?
Pls help me...
all textboxes are getting unchecked on postback
please help..........
@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
Thank you suresh.
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
this code is giving me error:
The name 'objUsers' does not exist in the current context"
how can i rectify this error?
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.
Hi, Sir.. This example was very helpful .. Can u please help me in editing and updating ..the seleted row using checkbox..
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??
Hello sir .. please same code in VB.net
this is my mail id
gprawin@gmail.com
Awsome
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();
}
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....
sir please start demo i want to see demo also
This is very helpful , i am a great fan of u ,
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
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
yes i m getting data in grid view still its showing Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index....
Note: Only a member of this blog may post a comment.