List Box Selected.value抛出null异常

Vee*_*eer 3 c# asp.net listbox

填充列表框如下:

if (ds != null)
{
    ListPreviousRecords.Items.Clear();

    ListPreviousRecords.DataSource = ds;
    ListPreviousRecords.DataTextField = "Date";
    ListPreviousRecords.DataValueField = "ID";
    ListPreviousRecords.DataBind();
}
Run Code Online (Sandbox Code Playgroud)

获取选定值:

protected void ListPreviousRecords_OnSelectedIndexChanged(object sender, EventArgs e)
{
    if(ListPreviousRecords.SelectedItem.Value != "")
    {
        int mySelectedValue = int.Parse(ListPreviousRecords.SelectedItem.Value);// throwing null exception
        loadPreviousDetails(mySelectedValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

Agh*_*oub 6

您可以添加此代码以确保输入非空值

if(!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem.Value ))
{
...
}
Run Code Online (Sandbox Code Playgroud)

并确保AutoPostBack="true"在您的控件上设置

链接:http://msdn.microsoft.com/fr-fr/library/system.string.isnullorempty.aspx