-2

having null reference exception. its a update code i am passing values from combobox to a local variable and then pass it into method.

pro_business sb = new pro_business();  //business layer class
string name = up_name.Text;  
sb.Ppro_name = name;
string type= type_combobox.SelectedItem.ToString(); //Having problem here!!)
string unit = unit_combobox.SelectedItem.ToString(); //Having problem here!!)
sb.Ppro_unit = unit;         
string message1 = sb.UpdateProductDetails(name, type, unit);
John Saunders
  • 157,405
  • 24
  • 229
  • 388
Bhargav Amin
  • 957
  • 3
  • 9
  • 20

1 Answers1

1

The reason for the exception is that SelectedItem is null, e.g. if the user did not select an entry yet. If you are only interested in the text of the item, rather use the Text property. If you want to check that the user has made a selection, use the SelectedIndex property.

In order to solve this, this code should work:

if (type_combobox.SelectedIndex >= 0 && unit_combobox.SelectedItem >= 0)
{
    pro_business sb = new pro_business();  //business layer class
    string name = up_name.Text;  
    sb.Ppro_name = name;
    string type= type_combobox.Text; 
    string unit = unit_combobox.Text;
    sb.Ppro_unit = unit;         
    string message1 = sb.UpdateProductDetails(name, type, unit);
}

For details on NullReferenceException and on how to fix it, see this excellent post.

Community
  • 1
  • 1
Markus
  • 15,389
  • 3
  • 25
  • 47