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 it's filled it will be parsed into a DateTime and then printed as the default ToString.

For each row, I 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. I'd 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 a problem with empty dates,

Convert.ToDateTime()

On an empty string, it will print the default DateTime.

Is there a way that I can fashion an If-Statement in my aspx code, to only perform Convert.ToDateTime, if it's not an empty string?

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

7 Comments

You can do this and avoid boxing by using DateTime? (nullable)
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.
It depends on what type of object is returned from the data source
I believe the type is a string
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>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.