Data Grid View With Textbox And Edit (Insert, Update, Delete) Option


In this demo use a grid view ,text boxes, buttons(Add, delete, update, cancel ) and Ajax calendar extender.

Use one table called “empinfo” it has 4 field

  1.       Id it is integer type and identity
  2.       Name it is nvarchar(100) for employee name
  3.       email_id it is nvarchar(300) for employee email id
  4.       dob it is nvarchar(20)  for employee date of birth


First complete concentrate on gird view

1. First focus on its column.
2. Give the style to it I use the style which is provided by the .net.
In this grid view use the four column

    1. id its not edit by the use it’s a label.
    2. txtname, txtemai_id, txtdob it edit by the use it’s textbox

3. Then on the c sharp code of grid view.

Grid view code

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="False" ShowFooter="true"

DataKeyNames="id,name,email_id,DOB" onrowediting="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting"

OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" OnRowCancelingEdit="GridView1_RowCancelingEdit">

Grid view code for style


<AlternatingRowStyle BackColor="White" ForeColor="#284775" />

<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" />

Grid view column code for creating the column


<Columns>

<asp:TemplateField HeaderText="ID" >

<EditItemTemplate>

<asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:Label ID="lblId" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText ="NAME" >

<EditItemTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Email">

<EditItemTemplate>

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("email_id") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("email_id") %>'></asp:TextBox>

</FooterTemplate>

<ItemTemplate>

<asp:Label ID="lblemail" runat="server" Text='<%# Bind("email_id") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="DOB">

<EditItemTemplate>

<asp:TextBox ID="txtDob" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDob">

</asp:CalendarExtender>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtDob" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDob">

</asp:CalendarExtender>

</FooterTemplate>

<ItemTemplate>

<asp:Label ID="lblDob" runat="server" Text='<%# Bind("DOB") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">

<EditItemTemplate>

<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/Images/update.png" ToolTip="Update" CausesValidation="True" CommandName="Update" AlternateText="Update"  ValidationGroup="e" />&nbsp;&nbsp;

<asp:ImageButton ID="ImageButton5" ImageUrl="~/Images/Cancel.png" runat="server" ToolTip="Cancel" CausesValidation="False" CommandName="Cancel" AlternateText="Cancel" />

</EditItemTemplate>

<FooterTemplate>

&nbsp;&nbsp;<asp:ImageButton ID="ImageButton3" runat="server" AlternateText="Add New Item" CommandName="AddNew" ToolTip="Add New Item" ValidationGroup="f" ImageUrl="~/Images/gvadd.png" />

</FooterTemplate>

<ItemTemplate>

<asp:ImageButton ID="ImageButton1" CausesValidation="false" CommandName="Edit" ImageUrl="~/Images/edit.png" ToolTip="Edit" AlternateText="Edit" runat="server" />&nbsp;&nbsp;

<asp:ImageButton ID="ImageButton2" ImageUrl="~/Images/Delete.png" ToolTip="Delete" CausesValidation="false" CommandName="Delete" AlternateText="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" runat="server" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

 Text='<%# Bind(“id”) %>’ is used for binding the table column “id” with grid view column.

Complete code of aspx page


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

&nbsp;

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

&nbsp;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

&nbsp;

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

&nbsp;

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Label ID="lblmsg" runat="server" Text="There is no data in gridview" Visible="false"></asp:Label>

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="False" ShowFooter="true"

DataKeyNames="id,name,email_id,DOB" onrowediting="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting"

OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" OnRowCancelingEdit="GridView1_RowCancelingEdit">

<AlternatingRowStyle BackColor="White" ForeColor="#284775" />

<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" />

<Columns>

<asp:TemplateField HeaderText="ID" >

<EditItemTemplate>

<asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:Label ID="lblId" runat="server" Text='<%# Bind("id") %>'></asp:Label>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText ="NAME" >

<EditItemTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>

</ItemTemplate>

&nbsp;

<FooterTemplate>

<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

&nbsp;

<asp:TemplateField HeaderText="Email">

<EditItemTemplate>

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("email_id") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("email_id") %>'></asp:TextBox>

</FooterTemplate>

<ItemTemplate>

<asp:Label ID="lblemail" runat="server" Text='<%# Bind("email_id") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

&nbsp;

<asp:TemplateField HeaderText="DOB">

<EditItemTemplate>

<asp:TextBox ID="txtDob" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDob">

</asp:CalendarExtender>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtDob" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDob">

</asp:CalendarExtender>

</FooterTemplate>

<ItemTemplate>

<asp:Label ID="lblDob" runat="server" Text='<%# Bind("DOB") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

&nbsp;

<asp:TemplateField HeaderText="Edit" ShowHeader="False">

<EditItemTemplate>

<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/Images/update.png" ToolTip="Update" CausesValidation="True" CommandName="Update" AlternateText="Update"  ValidationGroup="e" />&nbsp;&nbsp;

<asp:ImageButton ID="ImageButton5" ImageUrl="~/Images/Cancel.png" runat="server" ToolTip="Cancel" CausesValidation="False" CommandName="Cancel" AlternateText="Cancel" />

</EditItemTemplate>

<FooterTemplate>

&nbsp;&nbsp;<asp:ImageButton ID="ImageButton3" runat="server" AlternateText="Add New Item" CommandName="AddNew" ToolTip="Add New Item" ValidationGroup="f" ImageUrl="~/Images/gvadd.png" />

</FooterTemplate>

<ItemTemplate>

<asp:ImageButton ID="ImageButton1" CausesValidation="false" CommandName="Edit" ImageUrl="~/Images/edit.png" ToolTip="Edit" AlternateText="Edit" runat="server" />&nbsp;&nbsp;

<asp:ImageButton ID="ImageButton2" ImageUrl="~/Images/Delete.png" ToolTip="Delete" CausesValidation="false" CommandName="Delete" AlternateText="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" runat="server" />&nbsp;

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</ContentTemplate>

</asp:UpdatePanel>

</div>
</form>
</body>
</html>

For database connection Click Here

Code for filling the data grid view


protected void fillgridview()

{

qry = "select * from empInfo";

sds = new SqlDataSource(connection, qry);

GridView1.DataSource = sds;

if (sds != null)

{

lblmsg.Visible = true;

}

else

lblmsg.Visible = false;

GridView1.DataBind();

}

Code for binding the data with row


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

TextBox txtName = (TextBox)e.Row.FindControl("txtName");

if (txtName != null)

{

string Rag = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

txtName.Text = Rag.ToString().Trim();

}

TextBox txtEmail = (TextBox)e.Row.FindControl("txtEmail");

if (txtEmail != null)

{

string a = GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString();

txtEmail.Text = a.ToString().Trim();

}

TextBox txtDob = (TextBox)e.Row.FindControl("txtDob");

if (txtDob != null)

{

string a = GridView1.DataKeys[e.Row.RowIndex].Values[3].ToString();

txtDob.Text = a.ToString().Trim();

}

}

}

Code for edit the row


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

fillgridview();

}

Code for delete the row

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
qry = "delete from empInfo where id="+ id;
con = new SqlConnection(connection);
cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
if (cmd.ExecuteNonQuery() == 1)
fillgridview();
         }

Update the edit row

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtEmail = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmail");
TextBox txtDob = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDob");
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
qry = "update empInfo set name='" + txtName.Text + "',email_id='" + txtEmail.Text + "',DOB='" + txtDob.Text + "'where id='" + id + "'";
con = new SqlConnection(connection);cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
if (cmd.ExecuteNonQuery() == 1)
GridView1.EditIndex = -1;
fillgridview();
}

Code for cancel the update

<pre>protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}

Code for insert the new items

<pre>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtName");
TextBox txtEmail = (TextBox)GridView1.FooterRow.FindControl("txtEmail");
TextBox txtDob = (TextBox)GridView1.FooterRow.FindControl("txtDob");
qry = "insert into empInfo values('" + txtName.Text + "','" + txtEmail.Text + "','" + txtDob.Text +"')";
con = new SqlConnection(connection);
cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
cmd.ExecuteNonQuery();
fillgridview();

}

Complete code of “c sharp” file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
string qry;
string connection = "Data Source=.;Initial Catalog=test;Integrated Security=True";
SqlConnection con;
SqlCommand cmd;
SqlDataSource sds = new SqlDataSource();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgridview();

}
}
protected void fillgridview()
{
qry = "select * from empInfo";
sds = new SqlDataSource(connection, qry);
GridView1.DataSource = sds;
if (sds != null)
{
lblmsg.Visible = true;
}
else
lblmsg.Visible = false;
GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtName = (TextBox)e.Row.FindControl("txtName");
if (txtName != null)
{
string Rag = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
txtName.Text = Rag.ToString().Trim();
}
TextBox txtEmail = (TextBox)e.Row.FindControl("txtEmail");
if (txtEmail != null)
{
string a = GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString();
txtEmail.Text = a.ToString().Trim();
}
TextBox txtDob = (TextBox)e.Row.FindControl("txtDob");
if (txtDob != null)
{
string a = GridView1.DataKeys[e.Row.RowIndex].Values[3].ToString();
txtDob.Text = a.ToString().Trim();
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
qry = "delete from empInfo where id="+ id;
con = new SqlConnection(connection);
cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
if (cmd.ExecuteNonQuery() == 1)
fillgridview();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtEmail = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmail");
TextBox txtDob = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDob");
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
qry = "update empInfo set name='" + txtName.Text + "',email_id='" + txtEmail.Text + "',DOB='" + txtDob.Text + "'where id='" + id + "'";
con = new SqlConnection(connection);cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
if (cmd.ExecuteNonQuery() == 1)
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtName");
TextBox txtEmail = (TextBox)GridView1.FooterRow.FindControl("txtEmail");
TextBox txtDob = (TextBox)GridView1.FooterRow.FindControl("txtDob");
qry = "insert into empInfo values('" + txtName.Text + "','" + txtEmail.Text + "','" + txtDob.Text +"')";
con = new SqlConnection(connection);
cmd = new SqlCommand(qry, con);
if (con.State == ConnectionState.Open)
con.Close();
else
con.Open();
cmd.ExecuteNonQuery();
fillgridview();

}

}
}
}

Download the Sample Click Here

About these ads

4 thoughts on “Data Grid View With Textbox And Edit (Insert, Update, Delete) Option

  1. hello sir
    i am a student of c#.net. i need ur help. i am creating connection and connect sql server database.but when adding record there is an exception error at this point pls help me.
    DataRow drow = ds1.Tables[“alidb”].NewRow();
    thanks
    best regard

  2. Oh my goodness! Awesome article dude! Many thanks, However I am going
    through problems with your RSS. I don’t understand why I am unable to join it.
    Is there anyone else getting the same RSS issues? Anyone who knows the
    solution can you kindly respond? Thanx!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s