Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I have 2 list boxes lbabcList, lbxyzList and when I select the item from lbabcList box and click on the addbutton then it should go to lbxyzList box.

I am ending up with 'object reference not set to instance of object' error when I don`t select any item from the lbabcList box and click on addbutton.

How to solve this error

Here is my code in the addbutton_click.

Add the selected item to the event groups list
VB
lbxyzList.Items.Add(lbabcList.SelectedItem)

remove the event from the master list of events
VB
lbabcList.Items.Remove(lbabcList.SelectedItem)

lbxyzList.ClearSelection()


Thanks,
YesP
Posted
Updated 28-Aug-12 10:59am
v2

C#
if (lbabcList.SelectedItem != null){
    //add the selected item to the event groups list
    lbxyzList.Items.Add(lbabcList.SelectedItem)
 
    //remove the event from the master list of events
    lbabcList.Items.Remove(lbabcList.SelectedItem)
 
    lbxyzList.ClearSelection()
}
else{
   //Show a message if the user not selected an item
}


Hope it helps
 
Share this answer
 
You answered on your own! If nothing is selected , .SelectedItem will be null. Check it before trying to add. Or use the SelectedItemChanged[^] event to disable button if nothing is selected. If multiple selection is allowed, use SelectedItems[^] collection instead.
 
Share this answer
 
You need to check the item is null or not.
When you are not selecting anything in left listbox, the selected item is null and you are trying to add null object in right list box

Check the code here,
if(lbabcList..SelectedIndex >= 0){ //i.e not -1
  //do your add/remove stuff
}

OR

if(lbabcList.SelectedItem!=null){
   // do your add stuff
}

Hope this solves.
cheers
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900