Valerie Meunier

Valerie Meunier

  • 958
  • 693
  • 72.1k

The object reference is not set to an instance of an object.

Jan 16 2022 5:31 PM

Hi

I try to put 9 numbers from one textbox (windows forms) into 9 labels (label1, label2 ...from toolbox). I get" the object reference is not set to an instance of an object." at the line: lbl.Text = mat[i-1].ToString();

Thanks.

public partial class Form1 : Form
{
    int[] mat = new int[9];
    int g=0; int tel = 0;
    Label lbl = new Label();

    private void button1_Click(object sender, EventArgs e)
    {
        if (int.TryParse(textBox1.Text, out g) == true)
        {
            mat[tel] = g;
            tel++;
            if (tel == 9)
            {
                for (int i = 1; i <= 9; i++)
                {
                    lbl = (Label)Controls["label" + i.ToString()];
                    lbl.Text = mat[i-1].ToString(); // error
                }
            }
        }
    }
}

 


Answers (2)