UserControl array, each control has a method to set the text of a label there, but getting a NullReferenceException. Help!

StackOverflow https://stackoverflow.com/questions/1613350

Question

So, I create an array:

TorrentItem[] torrents = new TorrentItem[10];

The TorrentItem control has a method called SetTorrentName(string name):

private void SetTorrentName(string Name)
{
    label1.Text = Name;
}

I'm using a for loop to populate 10 TorrentItems like so:

private TorrentItem[] GetTorrents()
{
    TorrentItem[] torrents = new TorrentItem[10];
    string test = "";

    for (int i = 0; i < 10; i++)
    {
          test = i.ToString();
          TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
          //What am I doing wrong?
    }  
Was it helpful?

Solution

You create an array of references to 10 objects, but you do not create the 10 objects in the array. All array elements are null until initialized otherwise.

for( int i = 0; i < 10; ++i )
{
    torrents[i] = new TorrentItem();
    /* do something with torrents[i] */
}

However, the name initialization could probably be put into the constructor.

OTHER TIPS

You need to initialize each individual TorrentItem:

for (int i = 0; i < 10; i++)
{
      TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
      test = i.ToString();
      TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
      //What am I doing wrong?
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top