Hey guys,
This blog we will discuss how to delete
multiple selected checkbox form gridview.
We have a
table Like Person
Column Name
|
DataType
|
Allow Nulls
|
Id
|
int
|
No
|
Name
|
Varchar(50)
|
Yes
|
City
|
Varchar(50)
|
Yes
|
Deletemultiplerow.aspx
code:-
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:CheckBox ID="checkit" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblId" Text='<%#Eval("Id") %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" Text='<%#Eval("Name") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblcity" Text='<%#Eval("City") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" onclick="btnDelete_Click"
Text="Delete" />
Deletemultiple.aspx.cs file code:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["123"].ConnectionString);
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object
sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindit();
}
}
protected void bindit()
{
SqlDataAdapter sdr = new SqlDataAdapter("select * from person", con);
DataSet ds = new DataSet();
sdr.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chek = row.FindControl("checkit") as CheckBox;
if (chek.Checked)
{
var id = row.FindControl("lblId") as Label;
SqlCommand cmd = new SqlCommand("delete from person where
Id=@Id", con);
cmd.Parameters.AddWithValue("@Id", id.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
bindit();
}
}
No comments:
Post a Comment