Introduction
While fetching data from SQL tables to a webpage, adding data source to the
GridView comes foremost. The next big thing is to provide an interface to the
user so that data can be accessed, updated, removed in lesser clicks.
The lesser the process is hectic, more user friendly our interface becomes.
Moving forward, deleting multiple rows with a single button click is the first
step.
I prefer doing it by adding several lines during the declaration of GridView
design.
Adding a checkbox
A textbox is needed before displaying every row from the table.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="empid" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="empid" HeaderText="empid" InsertVisible="False" ReadOnly="True"
SortExpression="empid" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="password" HeaderText="password" SortExpression="password" />
<asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
<asp:BoundField DataField="country" HeaderText="country" SortExpression="country" />
</Columns>
</asp:GridView>
Adding 'Delete' Button afterall.
<asp:Button ID="btnDelete" runat="server" Text="Delete Selected" OnClick="btnDelete_Click"
Width="106px" />
Declaration of the function set at 'OnClick' of the button.
protected void btnDelete_Click(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data
Source=(local);Initial Catalog=Employee;Integrated Security=True");
con.Open();
int count
= 0;
for (int i
= 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("chk");
if (chk.Checked)
{
string id
= GridView1.DataKeys[i].Value.ToString();
SqlCommand
cmd = new SqlCommand("delete
from users where empid='"+id+"'",
con);
cmd.ExecuteNonQuery();
count++;
}
}
Response.Write("<script>alert('" +
count + " Rows Deleted!')</script>");
con.Close();
DataBind();
}