2009-10-23 14 views
1

Alors, je crée un tableau:Tableau UserControl, chaque contrôle dispose d'une méthode pour définir le texte d'une étiquette, mais en obtenant une exception NullReferenceException. Aidez-moi!

TorrentItem[] torrents = new TorrentItem[10]; 

Le TorrentItem contrôle a une méthode appelée SetTorrentName (string name):

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

J'utilise une boucle pour remplir 10 TorrentItems comme si:

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? 
    } 

Répondre

7

Vous créez un tableau de référen à 10 objets, mais vous ne créez pas les 10 objets dans le tableau. Tous les éléments du tableau sont null jusqu'à initialisation autrement. Cependant, l'initialisation du nom pourrait probablement être mise dans le constructeur.

2

Vous devez initialiser chaque individu 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? 
}