【问题标题】:Why am I getting a null reference exception when adding an ArrayList element to a ListBox?为什么将 ArrayList 元素添加到 ListBox 时出现空引用异常?
【发布时间】:2013-01-29 10:00:51
【问题描述】:

这段代码在注释行中出现“空引用异常”:

MessageBox.Show(string.Format("arrLst count is {0}", arrLst.Count));
for (int i = 0; i < arrLst.Count; i++)
{
    MessageBox.Show("Made it into for loop"); 
    listBoxCommandsSent.Items.Add(arrLst[i]); // <-- blows up here
    MessageBox.Show("Made it past first listBoxCommandsSent.Items.Add()");
    . . .

arrLst 是一个数组列表

第一个 MessageBox.Show 告诉我 arrLst 的计数为 8 到达第二个 MessageBox.Show(“进入 for 循环”) 第三个 MessageBox.Show 没有到达;所以,问题是将第 0 项添加到 listBox。

为什么会有问题?

注意:我使用 MessageBox.Show() 在调试器中单步执行它的原因在 SO 的其他地方都有记录;在 VS 2003 中,我无法从 XP 模式中连接到我的手持设备。

更新

甚至添加这些:

MessageBox.Show(string.Format("arrLst element 0 is {0}", arrLst[0].ToString()));
MessageBox.Show(string.Format("arrLst element 0 from i is {0}", arrLst[i].ToString()));

...告诉我我的期望(在这两种情况下,正如预期的那样):

arrLst element 0 is ! 0 200 200 210 1
arrLst element 0 from i is ! 0 200 200 210 1

我还在分配中添加了一个“ToString”,所以它现在是:

listBoxCommandsSent.Items.Add(arrLst[i].ToString());

...但无济于事。

【问题讨论】:

  • listBoxCommandsSent 是否为空?
  • 检查listBoxCommandsSent 不为空和listBoxCommandsSent.Items 不为空将是前两个要检查的。
  • Clay 你能显示你在哪里初始化arrLst 以及你在哪里初始化listBoxCommandsSent
  • 至于您的编辑,问题不可能是您正在添加的项目。即使他们是null,它也不会抛出那个异常。 listBoxCommandsSentnull
  • 我不明白列表框怎么可能是空的。我显然在这里遗漏了一些东西。

标签: c# arraylist listbox compact-framework windows-ce


【解决方案1】:

看来你没有初始化listBoxCommandsSentlistBoxCommandsSent.Items。你可以添加

if(listBoxCommandsSent==null)
    MessageBox.Show("listBoxCommandsSent is null");
if(listBoxCommandsSent.Items==null)
    MessageBox.Show("Items is null");

检查什么是空的。

【讨论】:

  • 我认为 listBoxCommandsSent 是空的,基于他对每个 MessageBox 正在做什么/显示的描述
  • arrList[0]=null 不应导致 listBoxCommandsSent.Items.Add(arrLst[i]) 中的空引用异常;行。
  • 列表框的Items 属性永远不会为空,也不需要由列表框的用户初始化。列表框本身可能为空。
  • 我不知道 listBoxCommandsSent 的类型是什么。他的代码中没有显示。
  • @KirillBestemyanov listBox 这个名字是一个非常明显的线索,而且他在描述 OP 中发生的事情时所指的事实是一个“列表框”。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2019-03-30
  • 1970-01-01
相关资源
最近更新 更多