[英]DateTime in ListBox C# Asp.Net
I would like to fill a listBox with DateTime. 我想用DateTime填充listBox。 So firstly, I've my code in ASP.NET
首先,我在ASP.NET中使用了我的代码
<table>
<tr>
<td>
<asp:ListBox
ID="ListBoxDate"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="ListBoxDate_SelectedIndexChanged" >
</asp:ListBox>
</td>
</tr>
</table>
This is in C# the method 这是C#的方法
protected void Page_Load(object sender, EventArgs e)
{
ListBoxDate.DataSource = GetAllDate(); /* it returns a list of objects Date (which is a class with an attribute DateTime) */
ListBoxDate.DataTextField = "_Date";
ListBoxDate.DataValueField = "_Date";
ListBoxDate.DataBind();
}
And the method ListBoxDate_SelectedIndexChanged when I click on the event : 单击事件时方法ListBoxDate_SelectedIndexChanged:
protected void ListBoxDate_SelectedIndexChanged(object sender, EventArgs e)
{
Date date= new Date()
{
_Date = ListBoxDate.SelectedValue,
};
}
And when I click on my date, I just recover an empty string and not a DateTime or a string containing the date. 当我点击我的日期时,我只是恢复一个空字符串而不是DateTime或包含日期的字符串。 (the listbox is OK when it displays on my browser)
(当我的浏览器显示时,列表框没问题)
I did the same principle with other attributes wich are string and it was OK. 我用其他属性做了相同的原则,这是字符串,没关系。 The problem is really the use of DateTime.
问题实际上是使用DateTime。
So, how can I recover the Date in after clicking on the listBox ? 那么,如何在点击listBox后恢复日期?
In Page_Load
, you have to check if is not a postback before databinding the ListBox. 在
Page_Load
,您必须在数据绑定ListBox之前检查是否不是回发。 Otherwise, the ListBox
will be repopulated before entering ListBoxDate_SelectedIndexChanged
and the SelectedValue
value will be lost: 否则,在进入
ListBoxDate_SelectedIndexChanged
之前将重新填充ListBox
,并且SelectedValue
值将丢失:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
ListBoxDate.DataSource = GetAllDate(); /* it returns a list of objects Date (which is a class with an attribute DateTime) */
ListBoxDate.DataTextField = "_Date";
ListBoxDate.DataValueField = "_Date";
ListBoxDate.DataBind();
}
}
Have in mind that the SelectedValue
property is a String, you'll have to parse its value to obtain a DateTime. 请记住,
SelectedValue
属性是一个String,您必须解析其值以获取DateTime。 You can using DateTime.Parse()
for that. 您可以使用
DateTime.Parse()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.