views:

797

answers:

2

I have a DateTime object that i need to print in a Custom Gridlike Control. The type of the data i want to print is a Date in the format dd-mm-yyyy. This value can be either filled or blank. If its filled it will be parsed into a DateTime and then printed as the default ToString.

For Each row, in can use

<CellTemplate>
    <asp:Literal ID="Literal2" runat="server" Text="<%# Container.Value %>"></asp:Literal>                               
</CellTemplate>

But this prints the default long version of the date. Id like the format from ToShortDateString().

So i tried modifying to:

<CellTemplate>
    <asp:Literal ID="Literal2" runat="server" Text="<%# Convert.ToDateTime(Container.Value).ToShortTimeString()%>"></asp:Literal>                               
</CellTemplate>

This works as intended.

Now i have the problem of empty dates.

Convert.ToDateTime()

On a empty string, will print the default DateTime.

Is there a way that i can fasion an If-Statement in my aspx code, to only perform Convert.ToDateTime if its not an empty string?

+1  A: 
Container.Value.Length > 0 ? Convert.ToDateTime(Container.Value).ToShortTimeString() : ""

You should also be able to pass Container.Value to any method in scope that you've defined.

Mark Cidade
Great Idea, unfortunately i cannot get your example to work.
Jesper Jensen
A: 

You can have a protected method in your code behind which does the checking for you

protected static string ConvertDate(object date) {
    if (date == null)
       return string.Empty;
    return Convert.ToDateTime(date).ToShortTimeString();
}
Bob
You can do this and avoid boxing by using DateTime? (nullable)
Will
This is a great idea. And ultimately my fallback solution. I would however like to learn how to do this purely inside the apsx page.
Jesper Jensen
It depends on what type of object is returned from the data source
Bob
I believe the type is a string
Jesper Jensen
You should be able to use marxidad's answer. Try putting his script block straight into the cell template without the literal <CellTemplate> <%# Container.Value.Length > 0 ? Convert.ToDateTime(Container.Value).ToShortTimeString() : "" %></CellTemplate>
Bob
You are correct. The <Literal>, for unknown reasons, did not allow the ? : statement. Without it, it now works perfectly fine
Jesper Jensen
The problem was with the quotes from Text="".In your script block you also use quotes, you can't nest quotes like that.
Bob