-1

When DeliveryMethodComboBox has no selectedItem, the

Object reference not set to an instance of an object.

error appears.

what is the best way to solve this? In this example i've added a try and catch.

try
{
    DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
catch 
{
    DeliveryMethodLabel2.Text = "";
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
JP..t
  • 575
  • 1
  • 6
  • 28
  • `NullReferenceException` is a common situation for beginner programmers. The link provided should help you understand the problem. Then use the debugger to find what/where/when you have a variable that is `null`. – Soner Gönül May 08 '15 at 12:42
  • 1
    The best way is the actually check whether an item has been selected. Don't use `try/catch` blocks for something like that. – Dirk May 08 '15 at 12:42
  • 1
    Think of exceptions as different than errors. When I talk to beginner programmers I tell them to think of an exception as "something they never saw coming." So for example, someone not selecting in a dropdown - you should expect this. It's common, it's going to happen. That makes it an error, not an exception. System is out of memory, that's an exception. It's not something we expect to happen normally. I hope that helps clarify a bit. – dmeglio May 08 '15 at 12:44
  • @Dirk i don't need to check if an item is selected, i need to know if the selectedItem is not null. But thank you! – JP..t May 08 '15 at 12:44
  • @dman2306 you mean, never do a catch when you know there is a possible error. Thanks – JP..t May 08 '15 at 12:54
  • @JP..t yeah. Exceptions are expensive in comparison to doing `if (foo == null)`. If you're expecting something to happen commonly, you should check it in an if statement. Doing a throw/catch means the CLR has to create a NullReferenceException object, unwind the stack to find a catch statement, handle it with whatever is in the catch, etc. That's a lot more work than comparing two values :) – dmeglio May 08 '15 at 17:02

1 Answers1

3

I'm assuming you mean that the value is null

** Assumes you don't have nulls in your list and that you are only concerned about whether there is a selection or not.

if(DeliveryMethodComboBox.SelectedIndex != -1)
{
    DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
else
{
    DeliveryMethodLabel2.Text = "";
}

Otherwise, if DeliverMethodComboBox can be null, just change the if to

if(DeliveryMethodComboBox != null && DeliveryMethodComboBox.SelectedIndex != -1)
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86