列表框对象引用错误 [英] List box object reference error

查看:105
本文介绍了列表框对象引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有2个列表框lbabcListlbxyzList,当我从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 [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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆