1

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

5
  • 1
    Create Popup_Data_Type_ComboBox before trying to access it. Commented Jun 26, 2013 at 18:12
  • this could be SelectedItem too tha equal to null. It's impossible to answer this question , without having more details about your app architecture. Commented Jun 26, 2013 at 18:13
  • You say "occurs on startup." There probably is not an item selected on startup Commented Jun 26, 2013 at 18:13
  • 1
    Either Popup_Data_Type_ComboBox or Popup_Data_Type_ComboBox.SelectedItem is null Commented Jun 26, 2013 at 18:13
  • where is the combo created? what is in the rest of the switch statement? Commented Jun 26, 2013 at 18:14

3 Answers 3

1

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 (...)
{

}
Sign up to request clarification or add additional context in comments.

Comments

1

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...
}

Comments

1

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())
        {
            //.....
        }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.