dmngrsk dmngrsk - 13 days ago 6
ASP.NET (C#) Question

DataTextFormatString not working in DropDownList

Let's say I'm writing an ASP.NET app that uses a

DropDownList
to display a single column, which contains
DateTime
objects, from a programatically created
DataTable
. I would like to use a specific format of
DateTime
, so I added a
DataTextFormatString
parameter to my
DropDownList
.

Page.aspx (website):

<asp:DropDownList ID="ddList1" runat="server"
DataTextField="MyDate" DataTextFormatString="{0:d}" />


Page.aspx.cs (script):

[...]

DataTable dt = new DataTable();
dt.Columns.Add("MyDate");

for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["MyDate"] = DateTime.Now.AddDays(i);
dt.Rows.Add(dr);
}

ddList1.DataSource = dt.DefaultView;
ddList1.DataBind();

[...]


However, that format does not change at all. If I add dummy text outside of
{0:d}
, it does appear on my page, but the
DateTime
object just does not want to format how I want it to. After looking for a solution, literally everyone says that I need to set
DataTextFormatString
properly. But come on, am I not doing that? What am I missing here?

Huge note: I would like
DataTextFormatString
to stay declarative (in Page.aspx).

Answer

The problem is in the DataTable, not The DataTextFormatString.

You need to specify the DataType of the column in the DataTable, otherwise it will default to string and you cannot apply formatting. So use

dt.Columns.Add("MyDate", typeof(DateTime));

And then the formatting in DataTextFormatString will work

DataTextFormatString="{0:dd-MM-yyyy}"