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"?
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}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With