I am creating a web application in asp.net 4.0
I have a web-form in which there is a ListBox control which adds a string list on Page_Load event. If I select any list item from ListBox and want to compute it by using Listbox.SelectedValue it throws Object reference not set to an instance of an object exception on Listbox.SelectedValue.
By using “QuickWatch” (in Visual studio 2010) i did some findings that i can get value by giving index (say Listbox.Items[2]) but i got null or -1 if i use Listbox.SelectedValue or Listbox.SelectedIndex
My problem is that why ListBox control is showing null exception error upon selection of item as this Listbox is not empty?
According to my understanding of the situation you are checking
Listbox.SelectedValueafterPage_Loadhas re-populated theListBoxso the SelectedIndex is reset i.e-1.and then you’re trying to check the
SelectedValueorSelectedIndexin the event handler,so it will be-1.Suggestions:
1. Populate ListBox on first time Page_Load.
2. Then after handling the event repopulate the
MyListBox.3. You should make a
protectedmethod for populatingListBox.Note: “null exception” is due to the fact that no item is selected i.e
-1(which is actually reset on Page_Load)