-1

New and noob programmer here.

Im trying to run this code and it compiles, but everytime I try to run it, I get this error.

Any Idea what might cause it and how to fix it?

public partial class Form2 : Form
{

  //Atributos (Se crea el array para los nombres)
  string[] listaJugadores = new string[5];

  Label[] listaLabels = new Label[5];

  public int contador = 0;

  public Form2()
  {
    InitializeComponent();
  }

  //Se activa el boton para mostrar los nombres registrados
  private void button1_Click(object sender, EventArgs e)
  {
    //Esto hara que se agureguen los nombres a la lista de jugadores
    listaJugadores[contador] = txtNombres.Text;
    listaLabels[contador].Text = txtNombres.Text;
    contador++;
    Random rnd = new Random();
    int value = rnd.Next(0, 10);
    textBox1.Text = value.ToString();
  }

}
  • 3
    `Label[] listaLabels = new Label[5];` allocates an array of 5 Labels, but each of the elements is still null. You have to assign a value to an element before you can set the Text. – Klaus Gütter Nov 09 '19 at 16:51

1 Answers1

0

You haven't created any labels for listaLabels so the exception.

All the five references are null by default.

You may create them in constructor for example:

public Form2()
{
  InitializeComponent();
  for ( int index = 0; index < listaLabels.Length; index++ )
    listaLabels[index] = new Label();
}

Or you need to assign cells from any that are design time created.

  • The thing is, the labels have been created in the form. I can't use those? – Pedro Monterroso Nov 09 '19 at 16:54
  • BTW, thanks for replying so quick! :) – Pedro Monterroso Nov 09 '19 at 16:54
  • The labels are not created. You created an array that can store five labels but the array content itself is five null references by default so you need to instantiate them one by one and assign each array cell to a reference to a label that you must create, or you can use some labels on the form dropped with the designer. –  Nov 09 '19 at 16:55
  • 1
    OH OH I get it now! Dumb me! THANKS A LOT! – Pedro Monterroso Nov 09 '19 at 16:57
  • If you're actually talking about labels on the form then you need to assign the entries in the array to the labels on the form. Unfortunately, you just have to do this one at a time--if your list is large it's often easier to create the components in question at runtime. – Loren Pechtel Nov 10 '19 at 07:20