We can dynamically assign the click events of button for example using that:
using System.Linq;
private void FormTest_Load(object sender, EventArgs e)
{
Controls.OfType<Button>()
.Where(b => b.Name.StartsWith("Button"))
.ToList()
.ForEach(b => b.Click += Button_Click);
}
We get all controls being type of button at the root level of the current form instance, filtered by the name matching the specified pattern, and we foreach on the resulting evaluation of the LINQ deferred query as a list to assign the event handler method.
If controls are for example in a panel:
MyPanel.Controls.OfType<Button>()...
Now we can dynamically change the text property using the tab index setted according to the expected result (Button1
has X
, Button2
has X+1
, and so on):
private void Button_Click(object sender, EventArgs e)
{
var button = sender as Button;
if ( button == null ) return;
button.Parent.Controls.OfType<Button>()
.Where(b => b.TabIndex > button.TabIndex)
.ToList()
.ForEach(b => b.Text = "");
}
If we need to search controls recursively in all the form or from a container having an inner hierarchy:
How to toggle visibility in Windows Forms C#
How to change BackColor of all my Panel in my Form
To use a different schema we also can use the predefined array, or list, of buttons solution suggested by @JohnnyMopp:
private void FormTest_Load(object sender, EventArgs e)
{
Buttons.Add(Button1);
Buttons.Add(Button2);
Buttons.Add(Button3);
Buttons.Add(Button4);
Buttons.ForEach(b => b.Click += Button_Click);
}
private void Button_Click(object sender, EventArgs e)
{
var button = sender as Button;
if ( button == null ) return;
Buttons.Where(b => b.TabIndex > button.TabIndex)
.ToList()
.ForEach(b => b.Text = "");
}
Also instead of using TabIndex
, we can use the Tag
for condition source, or even the list order itself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…