-2

I'm developing a UWP app where I need to display some contents of a file as entries in a ListBox like this:

I managed to read the file and use the parts that I want, but I stumbled upon an error that does not really make sense to me.

The app throws a NullReferenceException for a ListBoxItem array I'm using, even though I have initialized it before the for loop.

Here's part of the code I've written:

ListBoxItem[] item = new ListBoxItem[512]; //object initialization
for (int i = 0; i <= 511; i++)
{
    item[i].Content = "Preset " + (i + 1) + ":" + presets[i];
    //presets[] is an array I'm using to store the file contents before "merging" them to the item[] array
}
listBox1.Items.Clear();
listBox1.Items.Add(item); //after clearing the ListBox, display the contents of new file

I did check that part using breakpoints, and it seems that the item[] array is null, even though I have initialized it. I've also read other posts (such as this one), which were mostly forgotten initializations. Part of this answer on NullReferenceException, however, suggests that the array is allocated but never really initialized.

I'm at a loss, since I did develop the same app in WinForms a while back with mostly the same code and it did not have an initialization problem.

Any ideas as to why this happens?

1 Answer 1

3

new ListBoxItem[512] initializes just an empty array. After this you need to create an object of ListBoxItem type and add it to one of the array cell you want.

try this

ListBoxItem[] item = new ListBoxItem[512]; //array initialization
for (int i = 0; i <= 511; i++)
{
ListBoxItem itm = new ListBoxItem();  //object initialization
itm.Content = "Preset " + (i + 1) + ":" + presets[i];
item[i]=itm;
}
Sign up to request clarification or add additional context in comments.

3 Comments

It worked flawlessly. Thank you! Can you explain to me why do I need to initialize a second ListboxItem, though?
You are welcome. I added some explanations to my answer.
I understand it now. Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.