In this article, you will learn how to insert edit update delete in gridview in asp net c#
Introduction
In this post I will explain how to insert, edit, update and delete data in gridview using asp.net c#.
We have one gridview we need to write asp.net c# code to insert data into gridview than after that we need to edit that
gridview data and update it and if we want to delete the record in grdview we need to delete record
simply
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing
SqlConnection con = new SqlConnection("Data Source=PC-DK;Integrated Security=true;Initial Catalog=MyDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from EmployeeDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
How to insert edit update delete in gridview in asp net c#
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Asp.Net Repeater Control</title>
</head>
<body>
<form id="form1" runat="server">
<div style="font:13px Verdana;width:310px;">
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<h3>Asp.Net Repeater Control</h3>
<%--THE REPEATER CONTROL.--%>
<asp:Repeater id="rp" runat="server">
<%--HEADER OF THE REPEATER--%>
<HeaderTemplate>
<table border="0" width="200px">
</HeaderTemplate>
<%--SHOWING ITEMS--%>
<ItemTemplate>
<tr>
<td style="padding:2px;
border:solid 1px #CCC;">
<asp:Label Text='<%# Container.DataItem.ToString() %>'
runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
<%--ALTERNATE TEMPLATE (SHOWING ITEMS IN DIFFERENT COLOR--%>
<AlternatingItemTemplate>
<tr>
<td style="padding:2px;
border:solid 1px #CCC;
background:#EAF7FB;
width:200px;">
<asp:Label Text='<%# Container.DataItem.ToString() %>'
runat="server"></asp:Label>
</td>
</tr>
</AlternatingItemTemplate>
<%--REPEATER FOOTER--%>
<FooterTemplate>
</table>
<div style="padding:20px 0;">
<asp:Label ID="lblFoot" runat="server"></asp:Label>
</div>
</FooterTemplate>
</asp:Repeater>
<%--BUTTON CONTROL--%>
<asp:Button ID="btVF" Text="View Files" AutoPostBack="true"
OnClick="Show"
Font-Names="sanserif"
Font-Italic="true"
Font-Size="155%"
runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="PostBackTrigger" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {}
protected void Show(object sender, EventArgs e)
{
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath("Files\\"));
FileInfo[] fileList = Folder.GetFiles("*.*");
//BIND THE FILE LIST WITH THE REPEATER CONTROL.
rp.DataSource = fileList;
rp.DataBind();
}
}
Adding the <AlternatingTemplate> below the <ItemTemplate> will show files with a different background color for every alternate row.
<AlternatingItemTemplate>
<div style="padding:3px; border:solid 1px #FFF; background:#black">
<asp:Label Text='<%# Container.DataItem.ToString() %>' runat="server"></asp:Label>
</div>
</AlternatingItemTemplate>
</AlternatingItemTemplate>
<SeparatorTemplate><hr />
</SeparatorTemplate>
Add the <HeaderTemplate> element just above the <ItemTemplate>
<HeaderTemplate>
<div style="padding-bottom:20px"><strong>Files</strong> (Header)</div>
</HeaderTemplate>
Repeater with <FooterTemplate> element
<FooterTemplate>
<div style="padding-top:20px"><asp:Label ID="lblFooter" runat="server"></asp:Label></div>
</FooterTemplate>
Code Behind In C#
Control ft = rp.Controls[rep.Controls.Count - 1].Controls[0];
Label lbl_Footer = ft.FindControl("lblFooter") as Label;
lbl_Footer.Text = "Showing total <b>" + fileList.Length + "</b> files in the Footer.";