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 (lstChosen Subs.Selec tedItem.To String());
I guess I need to use the try and catch to handle this exception,right? Any idea how should I use it?
Regards,
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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(ls tSubjects. SelectedIt em.ToStrin g());)
}
}
catch (System.FormatException caught)
{
result.Text = caught.Message;
}
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
{
lstChosenSubs.Items.Add(ls
}
}
catch (System.FormatException caught)
{
result.Text = caught.Message;
}
catch (System.NullReferenceExcep tion caught)