Tableau UserControl, chaque contrôle a une méthode pour définir le texte d’une étiquette, mais en obtenant une exception NullReferenceException. Aidez-moi!
-
06-07-2019 - |
Question
Alors, je crée un tableau:
TorrentItem[] torrents = new TorrentItem[10];
Le contrôle TorrentItem a une méthode appelée SetTorrentName (nom de la chaîne) :
private void SetTorrentName(string Name)
{
label1.Text = Name;
}
J'utilise une boucle for pour peupler 10 TorrentItems comme suit:
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?
}
La solution
Vous créez un tableau de références à 10 objets, mais vous ne créez pas les 10 objets du tableau. Tous les éléments du tableau sont null
jusqu'à ce qu'ils soient initialisés sinon.
for( int i = 0; i < 10; ++i )
{
torrents[i] = new TorrentItem();
/* do something with torrents[i] */
}
Cependant, l'initialisation du nom pourrait probablement être placée dans le constructeur.
Autres conseils
Vous devez initialiser chaque TorrentItem individuel:
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?
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow