Pergunta

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.

Foi útil?

Solução

Here you go:

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top