0

Is there a way to move through objects in windows forms? (for example: buttons)

I want to disable a specific button based on an input. For Example: If I have 100 buttons, and got an input of 65, I want to make a loop that moves through all buttons until the 65th button. Is that possible?

Thanks!

H. Astrin
  • 21
  • 5
  • Look for `Controls` property of your form. Also `Name` or `Tag` properties of controls to distinguish between them. – Dialecticus Jul 22 '17 at 18:53
  • Well you could make a cascading function that iterates through form1.controls and the children looking for buttons. Not wery efficient though – Henrik Clausen Jul 22 '17 at 18:54
  • I hope you don't actually have 100 buttons in a form. That would be horrible. If you are making a Minesweeper game then better draw everything by yourself. – Dialecticus Jul 22 '17 at 18:57
  • Hehehehe it was an exaggeration, not going to have 100 buttons, it was just for the sake of the question :) – H. Astrin Jul 22 '17 at 19:06
  • Are those buttons created dynamically? Else you don't need looping. – Nikhil Vartak Jul 22 '17 at 19:19
  • No, I already created the buttons, just need to find a specific button and change it properties. – H. Astrin Jul 22 '17 at 19:23
  • Why not assign ID to these buttons then? IDs would be named like `btn1`, `btn2`.. `btnN` and then just pick desired one based on input without looping through all buttons. – Nikhil Vartak Jul 22 '17 at 19:26

1 Answers1

0

Keep your buttons in a List. Then send as a parameter to this function

private void EnabledButtons(List<Button> listButton, int count)
{
   foreach (Button btn in listButton)
   {
       btn.Enabled = false;
   }
   // or
   for (int i = 0; i < count; i++)
   {
       listButton[i].Enabled = false;
   }            
} 
Kemal Güler
  • 608
  • 1
  • 6
  • 21