Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to loop in buttons to save time and apply the function ElipsControl() to all buttons. Repetitive code


ex : ...
            ElipseControl nn = new ElipsControl(); 
            nn.CornerRadius = 20;
            nn.TargetControl = button3;
            nn.CornerRadius = 20;
            nn.TargetControl = button4;
            nn.CornerRadius = 20;
            nn.TargetControl = button5;
            nn.CornerRadius = 20;
            ...


What I have tried:

ElipseControl el = new ElipseControl();
            foreach (var btn in this.Controls)
            {
                if (btn.GetType() == typeof(Button))
                {
                    //((Button) btn).Controls;
                    el.TargetControl = (Button)btn;
                    el.CornerRadius = 20;
                }
            }

it don't work ?
Posted
Updated 10-Jun-21 19:35pm
v2
Comments
Maciej Los 9-Jun-21 3:23am    
We know what you want, but! we don't know what kind of issue do you have...
Can you be more specific and provide more details?
GSylvain55 9-Jun-21 10:13am    
I understand, but I try it and not working.
My buttons are in 3 panels.
Does that change anything ?
I change the modifier to public for panels.

C#Copy Code
foreach (var c in Controls)    {    //if (btn.GetType() == typeof(Button btn))      if (c is Button btn)         {           ElipseControl el = new ElipseControl();           el.TargetControl = (Control) btn;           el.CornerRadius = 20;         }

You definitely can't do it like that: you are creating a single instance of an ElipseControl and re-using it inside the loop. That means that each time round, you overwrite the settings you applied the previous time - and that means that the result will only be set for the last Button in your collection.
If you want to apply this to all buttons, you probably need to create a new instance of ElipseControl for each Button - and that means moving the code inside the loop. I'd also use more modern code for the loop body:
C#
foreach (Control c in Controls)
   {
   if (c is Button btn)
      {
      ElipseControl el = new ElipseControl();
      el.TargetControl = btn;
      el.CornerRadius = 20;
      }
   }
 
Share this answer
 
Comments
Maciej Los 9-Jun-21 4:37am    
5ed!
I find it, Yes !
It's work. I need just give de name of panels before.

C#
foreach (Control c in PanCla.Controls)
            {
                if (c is Button)
                {
                    
                    ElipseControl el = new ElipseControl();
                    el.TargetControl = c ;
                    el.CornerRadius = 20;
                }
            }

Thank You.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900