0

我想用 DateTime 填充一个列表框。所以首先,我在 ASP.NET 中有我的代码

<table>
    <tr>
        <td>&nbsp;
            <asp:ListBox 
                ID="ListBoxDate" 
                runat="server" 
                AutoPostBack="True"
                OnSelectedIndexChanged="ListBoxDate_SelectedIndexChanged" >
            </asp:ListBox>
        </td>
    </tr>
</table>

这是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();
}

当我单击事件时,方法 ListBoxDate_SelectedIndexChanged :

protected void ListBoxDate_SelectedIndexChanged(object sender, EventArgs e)
{
    Date date= new Date()
    {
        _Date = ListBoxDate.SelectedValue,
    };
}

当我点击我的日期时,我只是恢复一个空字符串,而不是 DateTime 或包含日期的字符串。(当它显示在我的浏览器上时,列表框是好的)

我对字符串的其他属性做了同样的原则,没关系。问题实际上是日期时间的使用。

那么,单击 listBox 后如何恢复 Date in ?

4

1 回答 1

2

Page_Load中,您必须在对 ListBox 进行数据绑定之前检查是否不是回发。否则,ListBox将在输入之前重新填充,ListBoxDate_SelectedIndexChanged并且该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();
    }
}

请记住,该SelectedValue属性是一个字符串,您必须解析它的值才能获得一个 DateTime。你可以使用DateTime.Parse()它。

于 2013-03-06T15:32:08.083 回答