列表框对象引用错误 [英] List box object reference error
问题描述
大家好,
我有2个列表框lbabcList
,lbxyzList
,当我从lbabcList
框中选择项目并单击addbutton
时,它应该转到lbxyzList
框.
当我没有从lbabcList
框中选择任何项目并单击addbutton
时,出现对象引用未设置为对象实例"错误.
如何解决此错误
这是我在addbutton_click
中的代码.
将所选项目添加到事件组列表中
lbxyzList.Items.Add(lbabcList.SelectedItem)
从事件的主列表中删除事件
lbabcList.Items.Remove(lbabcList.SelectedItem)
lbxyzList.ClearSelection()
谢谢,
YesP
if (lbabcList.SelectedItem!= 为空){ // 将所选项目添加到事件组列表中 lbxyzList.Items.Add(lbabcList.SelectedItem) // 从事件主列表中删除事件 lbabcList.Items.Remove(lbabcList.SelectedItem) lbxyzList.ClearSelection() } 其他 { // 如果用户未选择项目,则显示一条消息 }
希望对您有帮助
您自己回答了!如果未选择任何内容,则.SelectedItem
将为null.尝试添加之前检查它.或使用 SelectedItemChanged [ SelectedItems [ ^ ]集合.
您需要检查该项是否为空.
当您不在左侧列表框中选择任何内容时,所选项目为null,而您尝试在右侧列表框中添加空对象
在此处检查代码,
if(lbabcList..SelectedIndex >= 0){ //i.e not -1 //do your add/remove stuff } OR if(lbabcList.SelectedItem!=null){ // do your add stuff }
希望能解决.
欢呼
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
lbxyzList.Items.Add(lbabcList.SelectedItem)
remove the event from the master list of events
lbabcList.Items.Remove(lbabcList.SelectedItem)
lbxyzList.ClearSelection()
Thanks,
YesP
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
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.
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
这篇关于列表框对象引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!