2016-11-27 76 views
2

假设我正在编写一个ASP.NET应用程序,它使用DropDownList以编程方式创建的DataTable来显示单个列,其中包含DateTime对象。我想使用DateTime的特定格式,所以我在DropDownList中添加了一个DataTextFormatString参数。DataTextFormatString在DropDownList中不起作用

Page.aspx(网站):

[...] 

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

[...] 

Page.aspx.cs(脚本):

[...] 

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(); 

[...] 

然而,该格式并没有改变。如果我在{0:d}之外添加虚拟文本,它确实出现在我的页面上,但DateTime对象不想格式化我想要的格式。在寻找解决方案后,字面上每个人都说我需要正确设置DataTextFormatString。但是,来吧,我不是那样做?我在这里错过了什么?

巨大的笔记:我想DataTextFormatString保持声明(在Page.aspx)。

回答

2

问题出在DataTable,而不是DataTextFormatString

您需要指定DataTable中列的DataType,否则它将默认为字符串,并且不能应用格式。 因此,使用

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

然后在DataTextFormatString格式将工作

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

谢谢!如果不指定类型,我不知道'DataTable'自动将东西转换为字符串,但是当您考虑它时确实有意义。 – dmngrsk

相关问题