Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

c# - Is there a way to check buttons automatically

I've named all my buttons like Button1, Button2 ... I have 9 buttons named like these. I want my program to change the text of the buttons near it. For example: When Button3 is clicked, it should change Button4 to Button 9's texts to empty.

question from:https://stackoverflow.com/questions/65944328/is-there-a-way-to-check-buttons-automatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...