What is the best way to do button parameter change C#
When the event occurs, the text on all buttons should change. The code is presented below.
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";
Can I make it simpler, maybe like in arrays using a loop?
Solution 1:
Try adding the buttons in a list and then you can manipulate their text
property in a loop:
List<Button> btnLst = new List<Button>()
{
button1, button2, button3,
button4, button5, button6,
button7, button8, button9
};
foreach (Button btn in btnLst)
{
btn.text = "";
}
Solution 2:
Whatever container your buttons are in can be asked for its buttons. If they're not in any panel or group box and just sitting in the form they'll be in this.Controls
:
this.Controls
.OfType<Button>()
.Where(b => Regex.IsMatch(b.Name,"button[1-9]"))
.ToList()
.ForEach(b => b.Text = "");
You can probably skip the OfType too, as all controls have a Name and a Text..
If there's something else common about your buttons, such as they have the same tag it could be like
this.Controls
.OfType<Button>()
.Where(b => b.Tag == "Hello")
.ToList()
.ForEach(b => b.Text = "");
If all your buttons are in one panel, and nothing else is in there, or if there are other things that aren't buttons, it's easier because you can skip the where
this.ThePanel
.OfType<Button>()
.ToList()
.ForEach(b => b.Text = "");