In this video tutorial , I demonstrate that how we can delete records from grid view controls in asp.net.
I used stored Procedute for It.
GridViewEx.aspx
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
CellPadding=”4″ ForeColor=”#333333″ GridLines=”None”
onrowdeleting=”GridView1_RowDeleting”>
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
<Columns>
<asp:TemplateField HeaderText=”ID”>
<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text='<%# Eval(“id”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”User Name”>
<ItemTemplate>
<asp:Label ID=”Label2″ runat=”server” Text='<%# Eval(“name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Father Name”>
<ItemTemplate>
<asp:Label ID=”Label3″ runat=”server” Text='<%# Eval(“FatherName”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Salary”>
<ItemTemplate>
<asp:Label ID=”Label4″ runat=”server” Text='<%# Eval(“salary”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText=”Deletion” ShowDeleteButton=”True” />
</Columns>
<EditRowStyle BackColor=”#999999″ />
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<SortedAscendingCellStyle BackColor=”#E9E7E2″ />
<SortedAscendingHeaderStyle BackColor=”#506C8C” />
<SortedDescendingCellStyle BackColor=”#FFFDF8″ />
<SortedDescendingHeaderStyle BackColor=”#6F8DAE” />
</asp:GridView>
GridViewEx.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class GridViewEx : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“conn”].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}
}
public void fillgrid()
{
SqlDataAdapter da = new SqlDataAdapter(“sp_GetData”, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = ((Label)GridView1.Rows[e.RowIndex].FindControl(“Label1”)).Text;
SqlCommand cmd = new SqlCommand(“sp_Delete”, con);
cmd.Parameters.Add(new SqlParameter(“@id”,id));
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
{
fillgrid();
}
}
}
Stored Procedure
create proc sp_GetData
as
begin
select *from Employee
end