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?
CodePudding user response:
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;
}