Reputation:
I have a form that contains about 25 Buttons. I want to set the same property for the Multiple buttons based on user input. The properties i want to change are,
I have been able to do this using code but the Code is long. I want to know if there is a way to loop to change all of them.
This is what i used
button1.Text = btntext;
button1.ForeColor = btnforecolor;
button1.BackColor = btnbackcolor;
button1.Size = new Size(btnwidth, btnheight);
I had to do this like this for the 25 button, i want to know if there is any better way to do this with less code??..
Any suggestion will be appreciated.
Upvotes: 1
Views: 418
Reputation: 891
If you can't iterate through all of the buttons on a form but need a specific list of buttons I use this code.
List<Button> ListOfButtons = new List<Button>
{
this.Button1,
this.Button2,
}
foreach (Button myButton in ListOfButtons)
{
//Do your assigments to myButton
}
Upvotes: 0
Reputation: 8634
Two options here:
1) Create a list of buttons and loop:
for (int i = 0; i < 25; i++){
Button btn = new Button();
btn.Text = ...
btn.Location = new Point(10 + (i%5)*100, (i/5)*30);
btn.Click += new EventHandler(btn_Click); // TODO: Implement btn_Click event
this.Controls.Add(btn);
}
2) Loop through your existing controls:
foreach (Control c in this.Controls) {
Button btn = c as Button;
if (btn == null) continue;
btn.Text = ...
}
Upvotes: 2