Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET, how can I force the format of dates in a DropDownList to "DD/MM/YYYY"?

I have to build a DropDownList with the dates of the last 7 days. I would like the DropDownList displays the date as "DD/MM/YYYY". So I created a list of dates:

DateTime date = DateTime.Now;
List<DateTime> dates = new List<DateTime>();

for (int i = 0; i < HISTORY_LENGTH; i++)
{
    dates.Add(date.AddDays(-i));
}

DropDownList.DataSource = dates;
DropDownList.DataBind();

I add my dates as DateTime, not as strings. I think it is the method ToString() of my DateTime object that is called to create text that is visible in my DropDownList. By default it is the date and time. The result is:

[0]: {16/07/2008 11:08:27}

[1]: {15/07/2008 11:08:27}

[2]: {14/07/2008 11:08:27}

[3]: {13/07/2008 11:08:27}

[4]: {12/07/2008 11:08:27}

[5]: {11/07/2008 11:08:27}

[6]: {10/07/2008 11:08:27}

How can I force the format to "DD/MM/YYYY"?

like image 456
Bastien Vandamme Avatar asked Oct 31 '09 12:10

Bastien Vandamme


1 Answers

All you need to do is set DropDownList.DataTextFormatString - then upon DataBinding your control will apply the correct format:

<asp:DropDownList
    id="yourList"
    runat="server"
    dataTextFormatString="{0:dd/MM/yyyy}"/>
like image 55
Andrew Hare Avatar answered Oct 02 '22 22:10

Andrew Hare