Here we will shows how to delete multiple records from a GridView using a CheckBox in ASP.NET. This article is helpful in situations where user can delete row from the database. I have created a database named mailing in which we have a table named panku.
Here we will create database in sql server....
Database name----mailing
Tablename---panku
Field name---Mail_id—Primarykey(varchar(50))
Mail (varchar(50)
Mail_date(datetime)
Impliment design in Default.aspx page :-
- Drag
and Drop a GridView Control
from the toolbox and set AutoGenerateColumns
to false.
- Add
the Columns Collection that manages the collection of column fields.
- Add TemplateField inside the Columns
Collection that is used to display custom content in a data-bound control.
- Add
an ItemTemplate in the TemplateField that specifies the
content to display for the items in a TemplateField.
- Add
a CheckBox control inside the ItemTemplate.
- Inside
the Columns tag, we have added a column field BoundField that displays the
value of a field in a data source.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
CellPadding="4" AutoGenerateColumns="False"
DataKeyNames="Mail_id"
Width="577px" ForeColor="#333333" GridLines="None"
Height="59px" PageSize="2">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Mail_id" HeaderText="Mail_Id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Mail" HeaderText="Mail"
/>
<asp:BoundField DataField="M_date" HeaderText="Mail_date" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" /> </ItemTemplate> <HeaderTemplate>
<%--<input id="chkAll"
onclick="javascript:SelectAllCheckboxes(this);"
runat="server" type="checkbox" />--%>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#2A1C38" />
<HeaderStyle VerticalAlign="Top" Wrap="False" BackColor="#2A1C38"
ForeColor="White" />
</asp:GridView>
<br />
<br /> <asp:Button ID="Button2" runat="server" OnClick="Button1_Click" Text="Delete"
BackColor="#1F4983"
ForeColor="White"/>
Here we will implement code in Default.aspx.cs page....
protected void Page_Load(object
sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
SqlDataAdapter
ad = new SqlDataAdapter("select * from panku order by Mail_id",
con);
DataSet
ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object
sender, EventArgs e)
{
foreach
(GridViewRow row in
GridView1.Rows)
{
CheckBox
cb = ((CheckBox)(row.FindControl("chkSelect")));
if
(cb != null && cb.Checked)
{
string
Mailid = (GridView1.DataKeys[row.RowIndex].Value.tostring());
string
sqlstr = "delete from panku where Mail_id='"
+ Mail_id + "'"; SqlCommand mycmd;
mycmd = new SqlCommand(sqlstr, con);
con.Open();
mycmd.ExecuteNonQuery();
BindGridView();
}
con.Close();
}
}

No comments:
Post a Comment