Home > Enterprise >  Need solution to remove duplicate code in C#
Need solution to remove duplicate code in C#

Time:04-07

I'm using this right now to clear a tic tac toe table on Microsoft Windows Forms

            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            button4.Enabled = true;
            button5.Enabled = true;
            button6.Enabled = true;
            button7.Enabled = true;
            button8.Enabled = true;
            button9.Enabled = true;
            button1.Text = "";
            button2.Text = "";
            button3.Text = "";
            button4.Text = "";
            button5.Text = "";
            button6.Text = "";
            button7.Text = "";
            button8.Text = "";
            button9.Text = "";

but it's too long so I wanted to use a for loop like this

for (int i = 1; i < 10; i  )
{
   button[i].Enable = true;
   button[i].Text = "";
}

but it doesn't work so could anyone suggest a solution?

CodePudding user response:

you can iterate over Controls array of parent of buttons, for example you can move all buttons to a Panel and use foreach to iterate over all controls inside it:

foreach(var control in Panel1.Controls) {
    if (control is Button button)
    {
        button.Text = "";
        button.Enabled = true;
    }
}

CodePudding user response:

I see what you are thinking, but you cannot dynamically change the name of the variable you are trying to edit in a for loop like that.

In a for loop, it will iterate through a starting value until it reaches a stopping condition. for loops are great for when you have a data structure like a List or an Array where you can enumerate through to get or set values.

The code you have for the for loop is starting to enumerate through either an Array or List that has a name of button. To fix this, I recommend to add the buttons to an Array and then you can use a foreach loop to set the values:

foreach (Button button in buttons){
    button.Enabled = true;
    button.Text = "";
}
  • Related