Author Topic: Loop through each control  (Read 1526 times)

0 Members and 1 Guest are viewing this topic.

latour_g

  • Newt
  • Posts: 184
Loop through each control
« on: May 15, 2014, 03:36:38 PM »
I have a loop that goes through all the controls (all Button) in a panel.  For some reason, one button is ignore and one button is going twice in the loop.  Any idea why ?
 
Code: [Select]
            foreach (Control ct in this.panel2.Controls)
            {
                if (ct is Button)
                {
                    Button cbtn = (Button)ct;
                    lastBtn = cbtn;
                    if (cbtn.Name == cbtnName)
                    {
                        cbtn.BackColor = Color.Yellow; cbtn = btnLast;
                    }
                    else cbtn.BackColor = Color.Black;
                }
            }

Should I not use copy/paste to create my button ? I tried deleted the button and create another one but then it was another button that was being ignore  :ugly:

MickD

  • King Gator
  • Posts: 3666
  • (x-in)->[process]->(y-out) ... simples!
Re: Loop through each control
« Reply #1 on: May 15, 2014, 05:44:50 PM »
I don't know, but your logic with this line:

cbtn.BackColor = Color.Yellow; cbtn = btnLast;

is resetting your button back to normal, you save a copy as btnlast then copy it back over cbtn after you change it and returning it to its original state, this will make it look like it is being ignored yes?
"Programming is really just the mundane aspect of expressing a solution to a problem."
- John Carmack

"Short cuts make long delays,' argued Pippin.”
- J.R.R. Tolkien

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Loop through each control
« Reply #2 on: May 16, 2014, 12:31:10 AM »
Code: [Select]
cbtn = btnLast;
Why you do it? This changing is not used anywhere. Next loop override it (cbtn variable lives in the "if" construction only).
« Last Edit: May 16, 2014, 12:34:37 AM by Andrey Bushman »

latour_g

  • Newt
  • Posts: 184
Re: Loop through each control
« Reply #3 on: May 16, 2014, 09:29:29 AM »
btnLast is use elsewhere to put the button back to black.  But I have deleted btnLast to only keep lastBtn.  I have place lastBtn = cbtn;
 in the if statement and now it's working fine :

Code: [Select]
           
             foreach (Control ct in this.panel2.Controls)
            {
                if (ct is Button)
                {
                    Button cbtn = (Button)ct;
                   
                    if (cbtn.Name == cbtnName)
                    {
                        lastBtn = cbtn;
                        cbtn.BackColor = Color.Yellow;
                    }
                    else cbtn.BackColor = Color.Black;
                }
            }

Thank you guys you don't know how much time I spent on that problem !!!  You opened my eyes  :-D