handling null datetime in gridview

拜拜、爱过 提交于 2019-12-06 04:58:51

Here you go:

<%#  Eval("EmailTargetFirstSendDate") != null ? Convert.ToDateTime(Eval("EmailTargetFirstSendDate")).ToString("MM/dd/yyyy") : "No Date" %>

OK... I found a nice solutions (almost immediately after posting) Thanks MaxOvrdr for an answer, but I couldn't get it to work. I gave Stan credit as he nudged me in the right direction.

I added code behind:

    protected string GetDate(object  strDt)
    {
        DateTime dt1;
        if (DateTime.TryParse(strDt.ToString(), out dt1))
        {

            return dt1.ToString("MM/dd/yyyy");
        }
        else
        {
            return "";
        }


    }`

and modified the template text field to:

<asp:TemplateField > <HeaderTemplate> <asp:Label ID="lblHeadEmailFirstSendDate" runat="server" Text="1st Email<br />Target Date"></asp:Label> </HeaderTemplate> <ItemTemplate> <asp:Label ID="lblEmailFirstSendDate" runat="server" Text='<%# GetDate(Eval("EmailTargetFirstSendDate"))%>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="txtEmailFirstSendDate" Text='<%# GetDate(Eval("EmailTargetFirstSendDate"))%>'></asp:Label> </EditItemTemplate> </asp:TemplateField>

And Like Magic... it works!!! Thanks to all.

Use type DateTime? This will allow you to assign null to it

Adding the question mark turns it into a nullable type

Bind the data in the code behind? In the RowDataBound event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!