• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 460
  • Last Modified:

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,
0
operatortobe
Asked:
operatortobe
  • 3
1 Solution
 
AlexFMCommented:
Simple check can solve the problem:

if ( lstChosenSubs.Items.Count > 0 &&  lstChosenSubs.SelectedItem != null )
{
    lstChosenSubs.Items.Remove(lstChosenSubs.SelectedItem.ToString());
}
0
 
AlexFMCommented:
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.
0
 
operatortobeAuthor Commented:
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;
  }
0
 
AlexFMCommented:
catch (System.NullReferenceException caught)
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now