Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 82.4k

the name 'txt' doesn't exist in this context

Jan 2 2022 12:03 PM

Hi
i create dynamically 2 textbox, a label and a button. The purpose is to show the sum of the 2 textbox in the label  when clicking on the first button (created from Toolbox).
It works, but i get an error in line  foreach (TextBox t in txt) (the name 'txt' doesn't exist in this context).
Another question is: why gives Form1.Controls.Add(..) the error "an object reference is required") (must be Controls.Add(..) ) while panel1.Controls.Add(..) doesn't?
Thanks  a lot.

 private void button1_Click(object sender, EventArgs e)
        {
            int pointX = 30;
            int pointY = 40;
            panel1.Controls.Clear();
            TextBox[] txt = new TextBox[2];
            for (int i = 0; i < 2; i++)
            {
                txt[i] = new TextBox();
                txt[i].Name = "txt" + i.ToString();
                txt[i].Location = new Point(pointX, pointY);
                panel2.Controls.Add(txt[i]);
                pointY += 30;
            }

            Button bt = new Button();
            bt.Name = "button2";
            bt.Click += button2_Click;
            panel1.Controls.Add(bt);
            bt.Location = new Point(30, 30 * (aantal + 1) + 20);
            bt.Text = "sum";
            lbl.Location = new Point(120, 30 * (aantal + 1) + 25);
            panel1.Controls.Add(lbl);
        }

 private void button2_Click(object sender, EventArgs e)
        {
            int sum = 0;
            foreach (TextBox t in txt)
            {
                    sum += Convert.ToInt32(t.Text);
            }
            lbl.Text = sum.ToString();
        }


Answers (5)