0

I have got many buttons in my Application Form. And I would like to check every buttons text (compare). How can I achive that ?

for (i = 1; i < 30; i++) 
{
   if (this.button1.Text == "Hello") //here is PROBLEM
   {
      //..some statement
   }   
}

So next time this.button1.Text must change to this.button2.Text and so on...

this.button[i].Text not working.

casper_2
  • 43
  • 4

4 Answers4

4

Buttons are not arrays. Each one is a discreet object, and a child of its container.

Ideally, you need to build a collection (array, list, whatever) of the buttons and iterate through that collection, rather than using an index variable (i).

Here's a good approach: https://stackoverflow.com/a/3426721/820068

Community
  • 1
  • 1
Wesley Long
  • 1,708
  • 10
  • 20
  • you can iterate in windows form, and it's stated in the question that this is an application form – Anonymous Duck Jul 15 '16 at 04:07
  • @Desperado - I did not assert that any of that was false. You used exactly my approach by getting the panel.Controls collection and iterating through it. – Wesley Long Jul 15 '16 at 04:09
  • sorry I didn't click your link, you're correct we have the same concept and I copied my answer from my old code – Anonymous Duck Jul 15 '16 at 04:11
2

This is a correct syntax:

foreach (Control button in this.Controls)
{
     if (button.GetType() == typeof(Button) && button.Text == "Hello")
     {
           //..some statement    
     }
}
1

I'm quite sure that this is a windows form. And in windows form you can iterate the controls like this.

foreach (Control c in panel.Controls)
{
    string cType = c.GetType().ToString();

    // check all buttons
    if (cType == "System.Web.UI.WebControls.Button")
    {
        if(((Button)c).Text == "Hello")
        {

        }
    }
}

So what the code does is to iterate all the controls inside a panel and check each control if it's type is a button.

Update: As Wesley said, much better approach for the condition is to implement it like this

 if (c is Button && c.Text.Equals("Hello")) {
Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
0
for (int i = 1; i < 3; i++)
        {
            var buttonName = "button" + i;
            Button button = this.Controls.Find(buttonName, true).FirstOrDefault() as Button;
            string text = button.Text;
        }

try this code.

manoj
  • 150
  • 12
  • This might work for the given scenario, but its not recommendable in that it assumes that all the buttons should be named buttonX which is not a good nomenclature. – M22an Jul 15 '16 at 04:11
  • I know that. But Casper want to do this kind of behaviour. He wants to find a control by fixed names. Exp: http://stackoverflow.com/questions/3898588/find-control-by-name-from-windows-forms-controls – manoj Jul 15 '16 at 04:13