Hi indradeo,
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="GridView1" CssClass="Grid" runat="server" AutoGenerateColumns="false"
OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="Date" HeaderText="Date" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Drawing;
VB.Net
Imports System.Data
Imports System.Drawing
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Date", typeof(DateTime)) });
dt.Rows.Add("Shirt", new DateTime(2022, 02, 19, 15, 25, 00));
dt.Rows.Add("Jeans", DateTime.Now);
dt.Rows.Add("Trousers", new DateTime(2022, 02, 21, 05, 05, 00));
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime dateTime = Convert.ToDateTime(e.Row.Cells[1].Text);
if (dateTime.Subtract(DateTime.Now).TotalHours < 12)
{
e.Row.BackColor = Color.Green;
}
if (dateTime.Subtract(DateTime.Now).TotalHours > 24)
{
e.Row.BackColor = Color.Red;
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Item"), New DataColumn("Date", GetType(DateTime))})
dt.Rows.Add("Shirt", New DateTime(2022, 2, 19, 15, 25, 0))
dt.Rows.Add("Jeans", DateTime.Now)
dt.Rows.Add("Trousers", New DateTime(2022, 2, 21, 5, 5, 0))
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dateTime As DateTime = Convert.ToDateTime(e.Row.Cells(1).Text)
If dateTime.Subtract(DateTime.Now).TotalHours < 12 Then
e.Row.BackColor = Color.Green
End If
If dateTime.Subtract(DateTime.Now).TotalHours > 24 Then
e.Row.BackColor = Color.Red
End If
End If
End Sub
Screenshot