Question

I have a date field in a DataView that I would like to format to display "MM/DD/YYYY". The problem is I get this date from a service and I can't seem to format it in the Eval function where I set the field in my DataView.

<asp:GridView ID="gvTransactionHistory" runat="server" 
            AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="lblTransactionDate" runat="server" Text='<%# Eval("transactionDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView> 

I tried adding the String.Format("{mm/DD/yyyy}") to the Text property but that's not allowed. I also tried the Pre_Render event of the DataView but I am not running into much luck.

Was it helpful?

Solution

Format is the second parameter of Eval. The following should get you there:

<asp:Label ID="lblTransactionDate" runat="server" 
    Text='<%# Eval("transactionDate", "{0:MM/dd/yyyy}") %>'></asp:Label>

Notice that I changed the format string from mm/DD/yyyy to MM/dd/yyyy.

MM - Month

mm - Minute

DD - Not valid

dd - Day


Edit:

I assume your transactionDate may be a string. In that case, use the following:

<asp:Label ID="lblTransactionDate" runat="server" 
    Text='<%# String.Format("{0:MM/dd/yyyy}",DateTime.Parse(Eval("transactionDate").ToString())) %>'></asp:Label>

Above I have converted the string to a DateTime so that it can utilize the format.

OTHER TIPS

You can use this:

<asp:Label ID="lblTransactionDate" runat="server" Text='<%#String.Format("{0:MM/dd/yyyy}",Eval("transactionDate"))  %>'></asp:Label>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top