Dear Kankon,
Please refer below Sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView runat="server" ID="gvEmployees" AutoGenerateColumns="false" OnRowEditing="OnRowEditing"
OnRowCancelingEdit="OnRowCancelingEdit">
<Columns>
<asp:BoundField HeaderText="Employee Id" DataField="EmployeeID" ReadOnly="true" />
<asp:BoundField HeaderText="First Name" DataField="FirstName"/>
<asp:BoundField HeaderText="Last Name" DataField="LastName" />
<asp:TemplateField HeaderText="Hire Date">
<ItemTemplate>
<asp:Label Text='<%# Eval("HireDate","{0:yyyy-MM-dd}") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%# Eval("HireDate","{0:yyyy-MM-dd}") %>' TextMode="Date" />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true" HeaderText="Modify" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid ()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeId, FirstName, LastName, HireDate From Employees", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvEmployees.DataSource = dt;
gvEmployees.DataBind();
}
}
}
}
}
protected void OnRowEditing (object sender, GridViewEditEventArgs e)
{
gvEmployees.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelingEdit (object sender, GridViewCancelEditEventArgs e)
{
gvEmployees.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand("SELECT EmployeeId, FirstName, LastName, HireDate From Employees", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvEmployees.DataSource = dt
gvEmployees.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
gvEmployees.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvEmployees.EditIndex = -1
Me.BindGrid()
End Sub
Screenshot