Search code examples
c#arraylistlistboxcompact-frameworkwindows-ce

Why am I getting a null reference exception when adding an ArrayList element to a ListBox?


This code is blowing up on the commented line with "Null Reference Exception":

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 is an ArrayList

The first MessageBox.Show tells me arrLst has a count of 8 The second MessageBox.Show is reached ("made it into for loop") The third MessageBox.Show is not reached; so, the problem is adding item 0 to the listBox.

Why is this problematic?

Note: The reasons I'm using MessageBox.Show() insted of stepping through it in a debugger are documented elsewhere on SO; in a nuts hell, I can't connect to my handheld device from within XP Mode in VS 2003.

UPDATE

And even adding these:

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()));

...show me what I'd expect (in both cases, as is to be expected):

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

I also added a "ToString" to the assignment, so that it's now:

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

...but to no avail.


Solution

  • It seems that you did not initialize listBoxCommandsSent or listBoxCommandsSent.Items.You can add

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

    to check what is null.