简体   繁体   中英

List Box Selected.value throwing null exception

Populated list box like this:

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

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

Get selected value:

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

You can add this code in order to ensure that not null value is entered

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

And Ensure that AutoPostBack="true" is set on your control

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

Change:

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

To:

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

Use ListPreviousRecords.SelectedValue .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM