Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 81.5k

how to avoid repeating line in code?

Jan 10 2022 11:03 AM

Hi

I have 3 textbox in this windows forms project. I want to check the input (must be integer) and then show the sum of the three entered numbers.
This code works but i wonder whether it would be possible to avoid repeating te line "TextBox lbox = (TextBox)Controls["textBox" + i.ToString()];" in the 2nd loop. If i comment the line in the second loop, i get the  error "System.FormatException: The format of the input string is incorrect." at the next line.
If i don't define variable "TextBox lbox = new TextBox();", still commenting the line, i get the error in the second loop "the name 'lbox' doesn't exist in this context" (what i understand because lbox is only defined in the first loop).

So how to avoid the second line TextBox lbox = (TextBox)Controls["textBox" + i.ToString()]; ?

Thanks

public partial class Form1 : Form
    {
        bool b = true;
        int sum;
        TextBox lbox = new TextBox();
        public Form1()
        {  InitializeComponent(); }

        private void button1_Click_1(object sender, EventArgs e)
        {
            b = true;
            int txtg;
            for (int i = 1; i <= 3; i++)
            {
                TextBox lbox = (TextBox)Controls["textBox" + i.ToString()];
                if (int.TryParse(lbox.Text, out txtg) == false)
                {
                    b = false;
                    break;
                }
            }

            if (b == true)
            {
                for (int i = 1; i <= 3; i++)
                {
                    TextBox lbox = (TextBox)Controls["textBox" + i.ToString()];
                    sum += Convert.ToInt32(lbox.Text);
                }
            }
            label1.Text = sum.ToString();
        }
    }
}


Answers (2)