Convert TemplateField to DateTime - Blank Row

78 Views Asked by At

All of the dates are becoming empty even if there are dates present in the cell. This is from a gridview template field. I am trying to convert those cells that are not empty but instead, all of them are empty.

 asp:Label ID="Label13" runat="server" Text='<%# Eval("assigned_date") != null ? "" : Convert.ToDateTime(Eval("assigned_date")).ToString("MM/dd/yyyy")  %>'></asp:Label>
2

There are 2 best solutions below

3
Aristos On

It better to create a function on code behind and call that function - avoid the inline Eval. So the code will be as:

<asp:Label ID="Label13" runat="server" Text='<%# getDateTimeIfExist(Container.DataItem)%>'></asp:Label>

and on code behind

protected string getDateTimeIfExist(object oItem)
{
        var DateTimeToRender = DataBinder.Eval(oItem, "assigned_date") as DateTime?;

        if (DateTimeToRender != null)
            return DateTimeToRender.GetValueOrDefault().ToString("MM/dd/yyyy");
        else
            return string.Empty;
}
0
A.Mac On

Got it to work by checking for DBNull instead of null

The ? means then The : mean else

Text='<%# Eval("assigned_date") != DBNull.Value ? Convert.ToDateTime(Eval("assigned_date")).ToString("MM/dd/yyyy") : ""