List Box Selected.value抛出null异常

时间:2013-03-19 10:40:55

标签: c# asp.net listbox

这样填充的列表框:

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

    ListPreviousRecords.DataSource = ds;
    ListPreviousRecords.DataTextField = "Date";
    ListPreviousRecords.DataValueField = "ID";
    ListPreviousRecords.DataBind();
}

获取所选值:

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

3 个答案:

答案 0 :(得分:6)

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

if(!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem.Value ))
{
...
}

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

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

答案 1 :(得分:1)

变化:

 if(ListPreviousRecords.SelectedItem.Value != "")

要:

  if (!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem))

答案 2 :(得分:0)

使用ListPreviousRecords.SelectedValue

if (!string.IsNullOrWhiteSpace(ListPreviousRecords.SelectedValue)) {
    // ...
}