Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need solution to remove duplicate code in C#

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 = "";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading