List Box Selected.value throwing null exception

asp.net, c#, listbox

Solution

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

Problem

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); } } ```

Original source