In this asp.net tutorial you will learn how to delete multiple rows in gridview in asp.net using c#. During web development in number of occasions you may get requirement to delete the multiple rows in a gridview. In asp.net it is not difficult. Let's have a look over how to do so.
Delete multiple rows from gridview in asp.net using c#
.aspx
<asp:gridview id="GridView1" runat="server" width="100%"> <Columns> <asp:TemplateField HeaderText="Delete"> <ItemTemplate> <asp:CheckBox ID="chkid" runat="server" Text='<%# Bind("User_ID")%>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Email" > <ItemTemplate> <asp:Label ID="lbl_Email" Text='<%# Bind("User_Email")%>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Font-Size="15px" /> </asp:TemplateField> <asp:TemplateField HeaderText="First Name" > <ItemTemplate> <asp:Label ID="lbl_first_name" Text='<%# Bind("User_First_Name")%>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Font-Size="15px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Last Name" > <ItemTemplate> <asp:Label ID="lbl_last_name" Text='<%# Bind("User_Last_Name")%>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Font-Size="15px" /> </asp:TemplateField> </Columns> </asp:gridview>
.aspx.cs
protected void Button1_Click(object sender, EventArgs e) { foreach(GridViewRow row in GridView1.Rows) { CheckBox chkbox = (CheckBox)row.FindControl("chkid"); string uid = chkbox.Text; if (chkbox.Checked) { con.ConnectionString=strcon; com.Connection=con; con.Open(); string query = "Delete from users where User_ID='"+uid+"'"; com.CommandText = query; com.ExecuteNonQuery(); con.Close(); fillgrid(); } } }
Now let's first understand the code written in .aspx page.
I just put a gridview control in my aspx page just like the tutorial I have written to Displaying data from database in gridview. The only difference is that in very first <asp:TemplateField> I put a checkbox inside its <ItemTemplate> and give the checkbox User_ID as a Text which is the primary key in my users table. It is very much compulsory to provide unique/primary key to the checkbox so that deletion of multiple rows can be achieved without any problem. And then in the end, just below the gridview control I put the asp:button and using its server side onClick event I have written the code to delete the multiple rows in a gridview.
In above code snippet I am using the foreach loop which simply goes to each row of the gridview and then check whether the checkbox of that row is checked or not, if the checkbox of that row is checked then it will simply delete that row.
In the last I made call to the fillgrid() function to display the remaining records in gridview after deletion process. As I have already written this fillgrid() function in my previous tutorial Displaying data from database in gridview that's why in this post i avoid extra code. So That's it
Happy Coding!!!
0 comments:
Post a Comment