Hi mansoorkpy,
Refer below example.
HTML
<asp:GridView runat="server" ID="gvTimes" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="StartTime" HeaderText="Start" DataFormatString="{0:HH:mm}" />
<asp:BoundField DataField="EndTime" HeaderText="End" DataFormatString="{0:HH:mm}" />
<asp:TemplateField HeaderText="Difference">
<ItemTemplate>
<asp:Label ID="lblDiff" runat="server" Text="0" />
</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)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("StartTime", typeof(DateTime));
dt.Columns.Add("EndTime", typeof(DateTime));
dt.Rows.Add(1, DateTime.Now, DateTime.Now);
dt.Rows.Add(2, DateTime.Now.AddHours(1), DateTime.Now);
dt.Rows.Add(3, DateTime.Now.AddHours(2), DateTime.Now);
gvTimes.DataSource = dt;
gvTimes.DataBind();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i < dt.Rows.Count - 1)
{
DateTime endTime = Convert.ToDateTime(dt.Rows[i][2]);
DateTime startTime = Convert.ToDateTime(dt.Rows[i + 1][1]);
(gvTimes.Rows[i + 1].FindControl("lblDiff") as Label).Text = startTime.Subtract(endTime).Hours.ToString();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("StartTime", GetType(DateTime))
dt.Columns.Add("EndTime", GetType(DateTime))
dt.Rows.Add(1, DateTime.Now, DateTime.Now)
dt.Rows.Add(2, DateTime.Now.AddHours(1), DateTime.Now)
dt.Rows.Add(3, DateTime.Now.AddHours(2), DateTime.Now)
gvTimes.DataSource = dt
gvTimes.DataBind()
For i As Integer = 0 To dt.Rows.Count - 1 Step 1
If i < dt.Rows.Count - 1 Then
Dim endTime As DateTime = Convert.ToDateTime(dt.Rows(i)(2))
Dim startTime As DateTime = Convert.ToDateTime(dt.Rows(i + 1)(1))
TryCast(gvTimes.Rows(i + 1).FindControl("lblDiff"), Label).Text = startTime.Subtract(endTime).Hours.ToString()
End If
Next
End If
End Sub
Screenshot