每次我运行代码时,都会得到System.NullReferenceException

时间:2019-11-09 16:47:43

标签: c#

新手和菜鸟程序员在这里。

我正在尝试运行此代码并将其编译,但是每次尝试运行它时,都会出现此错误。

任何想法可能会导致它以及如何解决它?

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();
  }

}

1 个答案:

答案 0 :(得分:1)

您尚未为listaLabels创建任何标签,因此例外。

默认情况下,所有五个引用均为空。

您可以在构造函数中创建它们,例如:

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

或者您需要从设计时创建的任何单元中分配单元格。

相关问题