Hi kankon,
Refer below sample.
HTML
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="true" />
<asp:BoundField DataField="User" HeaderText="User" />
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:HiddenField ID="hfDOB" runat="server" Value='<%# Eval("DOB") %>' />
<asp:Label ID="lblAge" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id"),
new DataColumn("User"),
new DataColumn("DOB", typeof(DateTime))
});
dt.Rows.Add(1, "John Hammond", "2022/05/05");
dt.Rows.Add(2, "Mudassar Khan", "2004/04/04");
dt.Rows.Add(3, "Suzanne Mathews", "2005/03/03");
dt.Rows.Add(4, "Robert Schidner", "2000/02/02");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime dob = Convert.ToDateTime((e.Row.FindControl("hfDOB") as HiddenField).Value);
int current = DateTime.Today.Year;
(e.Row.FindControl("lblAge") as Label).Text = (current - dob.Year).ToString();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("User"), New DataColumn("DOB", GetType(DateTime))})
dt.Rows.Add(1, "John Hammond", "2022/05/05")
dt.Rows.Add(2, "Mudassar Khan", "2004/04/04")
dt.Rows.Add(3, "Suzanne Mathews", "2005/03/03")
dt.Rows.Add(4, "Robert Schidner", "2000/02/02")
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dob As DateTime = Convert.ToDateTime((TryCast(e.Row.FindControl("hfDOB"), HiddenField)).Value)
Dim current As Integer = DateTime.Today.Year
(TryCast(e.Row.FindControl("lblAge"), Label)).Text = (current - dob.Year).ToString()
End If
End Sub
Screenshot