hi
a have a gridview with datafield column which is bound to a datetime column.
i want the grid column to show the date when the day is first, like this: 24/2/2009

i tried the following format:

DataFormatString="{0:dd/MM/YYYY}"

but the grid is still shows the date when the month is first.
where was i wrong ?

Dani AI

Generated

A few things to check — two separate problems are common here: a format-string typo and the GridView/BoundField behavior (encoding or wrong source type).

Format tokens are case-sensitive: the year token is lowercase y (four y for a four‑digit year) and months are M (not m, which means minutes). Also the DataFormatString must include the parameter placeholder (the 0 in {0:...}). See the .NET docs for the custom date/time specifiers. (learn.microsoft.com)

Even with the correct token you can still see the unformatted value if the BoundField is HTML-encoding the data before formatting. That historically caused DataFormatString to be ignored; many people fixed it by disabling HTML encoding for the field or, on newer ASP.NET versions, by using the HtmlEncodeFormatString option so the formatting happens before encoding. This is the behavior was pointing at and is explained in older writeups and MS docs. (weblogs.asp.net)

Practical options (pick one that fits the project):

  • Convert the BoundField to a TemplateField and format the value yourself (works even when the source is a string):
<asp:TemplateField HeaderText="Date">
  <ItemTemplate>
    <%# Convert.ToDateTime(Eval("date")).ToString("dd/MM/yyyy") %>
  </ItemTemplate>
</asp:TemplateField>
  • Or format in the RowDataBound event if you prefer server-side control:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var raw = DataBinder.Eval(e.Row.DataItem, "date")?.ToString();
        if (DateTime.TryParse(raw, out DateTime dt))
            e.Row.Cells[1].Text = dt.ToString("dd/MM/yyyy");
    }
}

TemplateField/RowDataBound usage is covered in the ASP.NET docs. If your column is actually coming through as a string (for example an ISO datetime text), DataFormatString on a BoundField won’t parse it — either return a proper DateTime from the query or parse it in a template/RowDataBound handler. (learn.microsoft.com)

Quick checklist:

  • Confirm the format tokens are correct (yyyy, MM, etc.). (learn.microsoft.com)
  • Verify the field’s data type is DateTime (or parse it in a template). (stackoverflow.com)
  • If you keep a BoundField, control HTML encoding so the formatted string is used (see HtmlEncodeFormatString/HtmlEncode). (learn.microsoft.com)

Notes tied to the thread: was right about case-sensitivity; correctly pointed out the HtmlEncode interaction; ’s template suggestion is the most robust route if the DB column is a string.

Recommended Answers

All 9 Replies

it is case sensitive, try this :

{0:dd/MM/yyyy}

the total example is this :

Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="PKID" DataSourceID="SqlDataSource1" 
        EmptyDataText="There are no data records to display.">
        <Columns>
            <asp:BoundField DataField="PKID" HeaderText="PKID" ReadOnly="True" 
                SortExpression="PKID" />
            <asp:BoundField DataField="date" DataFormatString="{0:dd/MM/yyyy}" 
                HeaderText="date" SortExpression="date" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:denemeConnectionString1 %>" 
        DeleteCommand="DELETE FROM [Table1] WHERE [PKID] = @PKID" 
        InsertCommand="INSERT INTO [Table1] ([date]) VALUES (@date)" 
        ProviderName="<%$ ConnectionStrings:denemeConnectionString1.ProviderName %>" 
        SelectCommand="SELECT [PKID], [date] FROM [Table1]" 
        UpdateCommand="UPDATE [Table1] SET [date] = @date WHERE [PKID] = @PKID">
        <DeleteParameters>
            <asp:Parameter Name="PKID" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter DbType="Date" Name="date" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter DbType="Date" Name="date" />
            <asp:Parameter Name="PKID" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

i tryed it the way you suggested with small letters:
DataFormatString="{0:dd/MM/yyyy}"

it still doesnot work.

my full code line is:

<asp:BoundField DataField="date" DataFormatString="{:dd/MM/yyyy}"  HeaderText="date" />

The problem is the by default, the HtmlEncode property of the boundfield attribute is set to True. This helps prevent cross-site scripting attacks and malicious content from being displayed. Microsoft recommends that the HtmlEncode attribute be enabled whenever possible.

The problem is that if this field is enabled, you can not pass format information to the boundfield control. To solve this issue simply set HtmlEncode to false

Try this:

<asp:BoundField DataField="date" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"  HeaderText="date" />

well i tryed this and it still doesnot work.

Still not resolved??????????

just try this:

{d:0}

Works for me!

well i tryed this and it still doesnot work.

Hi

try this example:

<asp:BoundField DataField=”date_from” HeaderText=”DateApply” 
     HeaderStyle-Width =”350px” DataFormatString=”{0:MM/dd/yyyy}” HtmlEncode=”false”>

//—–another way

<asp:TemplateField HeaderText=”Date Submission” SortExpression=”DateSubmission”>
                <ItemTemplate>
                    <asp:Label ID=”Label1″ runat=”server” Text=’<%# Bind(”DateSubmission”, “{0:dd/MM/yyyy}”) %>’></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign=”Center” />
            </asp:TemplateField>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.