La matriz UserControl, cada control tiene un método para establecer el texto de una etiqueta allí, pero obteniendo una NullReferenceException. ¡Ayuda!

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

Pregunta

Por lo tanto, creo una matriz:

TorrentItem[] torrents = new TorrentItem[10];

El control TorrentItem tiene un método llamado SetTorrentName (nombre de cadena) :

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

Estoy usando un bucle for para completar 10 TorrentItems así:

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?
    }  
¿Fue útil?

Solución

Crea una matriz de referencias a 10 objetos, pero no crea los 10 objetos en la matriz. Todos los elementos de la matriz son null hasta que se inicialicen de otra manera.

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

Sin embargo, la inicialización del nombre probablemente podría incluirse en el constructor.

Otros consejos

Necesita inicializar cada TorrentItem individual:

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?
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top