【发布时间】: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,它也不会抛出那个异常。listBoxCommandsSent是null。 -
我不明白列表框怎么可能是空的。我显然在这里遗漏了一些东西。
标签: c# arraylist listbox compact-framework windows-ce