DataList ItemDataBound Event to Compare two Dates

Introduction

I have written following code for DataList Compare Two Date in ItemDataBound Event.The code is useful to find datalist control in ItemDataBound. ItemDataBound events gives access to item inside datalist the DataList or you can access the item’s value.

Using Code

Step 1: Create A DataList

  1. <asp:DataList ID="dlDate" runat="server" Style="width: 100%" OnItemDataBound="dlDate_ItemDataBound">  
  2.     <ItemTemplate>  
  3.         <asp:Label ID="lblDate" Text='<%#Eval("DateTime")%>' runat="server">  
  4.         </asp:Label>  
  5.     </ItemTemplate>  
  6. </asp:DataList>  

Step 2: Use OnItemDataBound Event

  1. protected void dlDate_ItemDataBound(object sender, DataListItemEventArgs e)  
  2. {  
  3.     if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)  
  4.     {  
  5.         Label lblDate = (Label) e.Item.FindControl("lblDate");  
  6.         DateTime dtDateTime = Convert.ToDateTime(lblDate.Text);  
  7.         DateTime dtCurrentDatetime = Convert.ToDateTime(System.DateTime.Now);  
  8.         int result = DateTime.Compare(dtDateTime, dtCurrentDatetime);  
  9.         if (result == -1)  
  10.         {  
  11.             lblDate.Style.Add("text-decoration""line-through");  
  12.         }  
  13.     }  
  14. }  

You can apply any css and change text in lblDate.