handling null datetime in gridview

余生长醉 提交于 2019-12-10 10:55:03

问题


I have a gridview in C# asp.net Web 4.5 Framework that works great until a null valued is passed for a field I am formatting as a date..

here is my template field

<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='<%#  Convert.ToDateTime(Eval("EmailTargetFirstSendDate")).ToString("MM/dd/yyyy")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:Label runat="server"  ID="txtEmailFirstSendDate" Text='<%#Convert.ToDateTime(Eval("EmailTargetFirstSendDate")).ToString("MM/dd/yyyy")%>'></asp:Label>
    </EditItemTemplate>
</asp:templatefield>

I've searched high and low to find a solution that both allows me to format the date and doesn't generate an exception when the date is null.


回答1:


Here you go:

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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23685016/handling-null-datetime-in-gridview

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