yawnobleix
yawnobleix

Reputation: 1342

Reference not set to instance error

I am getting the error "reference not set to an instance of an object" when the following code occurs on startup:

  switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
            {

I am pretty sure that this error is occurring as Popup_Data_Type_ComboBox has not yet been created therefore its not possible to get the sting value. How Can I get around this problem?

Ok thanks a lot for all the help I threw in a check if Popup_Data_Type_ComboBox.SelectedItem == null and it now works fine

Upvotes: 1

Views: 215

Answers (3)

CodeCaster
CodeCaster

Reputation: 151594

Add a check before the switch, assuming the code is in a method that just handles the Popup_Data_Type_ComboBox.SelectionChanged-event or the likes:

if (Popup_Data_Type_ComboBox == null 
    || Popup_Data_Type_ComboBox.SelectedIndex < 0)
{
    // Just return from the method, do nothing more.
    return;
}

switch (...)
{

}

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

I'd verify first that Popup_Data_Type_ComboBox is instantiated, and then verify that an item is selected. If you are running this on startup as you said, then it is likely no item is selected. you can check with:

if(Popup_Data_Type_ComboBox.SelectedItem != null)
{
    switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
        {
            //.....
        }
 }

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

The most likely issue is that your combo box hasn't been created, or doesn't have a selected item. In this case, you'd have to explicitly handle that:

if (Popup_Data_Type_ComboBox != null && Popup_Data_Type_ComboBox.SelectedItem != null)
{
    switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
    {
        //... 
    }
}
else
{
   // Do your initialization with no selected item here...
}

Upvotes: 1

Related Questions