Link to home
Start Free TrialLog in
Avatar of operatortobe
operatortobe

asked on

NUll Reference exception was not handled

Hi there,
I have 2 lists boxes. The 1st one has multiple items. The 2nd listbox is empty. The user selects the items to be transferred to the 2nd listox and hits the ADD button. The process works the other way if the user wants to get rid of the items selected on the 2nd listbox. I just had a chance to check the adding items from listbox1 to listbox2. It works fine, however if the user doesn't choose ant item from the listbox1 and just hits the ADD button I get this following message;

"NUll Reference exception was not handled"
lstChosenSubs.Items.Remove(lstChosenSubs.SelectedItem.ToString());

I guess I need to use the try and catch to handle this exception,right? Any idea how should I use it?
Regards,
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AlexFM
AlexFM

We need to use exception handling in methods which suppose to throw exceptions - like different I/O methods. Null reference exception is just bug - if you catch it, you can hide your own bugs like using uninitialized references.
Avatar of operatortobe

ASKER

Hi Alex,
I have tried your code and it works just fine. I have also modified it and applied it to Add button as well. Thanks much. I just wonder what if I wanted to use Try and catch instead... Would it be some thing like this;

try
  {
    if(lstSubjects.Items.Count > 0 && lstSubjects.SelectedItem != null)
            {

                lstChosenSubs.Items.Add(lstSubjects.SelectedItem.ToString());)
       }
   }
catch (System.FormatException caught)
     {
          result.Text = caught.Message;
  }
catch (System.NullReferenceException caught)