4

How to change the property of a control in a flowlayoutpanel assuming that you add the controls programatically and assuming that the name of each controls are the same?

For example this image shows you that there are 2 text boxes and two buttons, how would I change the back color of button 2? Assuming the controls has been added at runtime.

alt text

foreach(Controls ctrl in flowlayoutpanel1.Controls)
{
//What should I put here?
}
Rye
  • 2,273
  • 9
  • 34
  • 43

2 Answers2

4

Well, the easiest way would be to retain an explicit reference to the buttons you're adding. Otherwise you could add a tag to distinguish them (to be robust against i18n issues). E.g. you can set the tag of "button2" to "button2" and then you can use:

foreach (Control ctl in flp.Controls) {
    if ("button2".Equals(ctl.Tag)) {
        ctl.BackColor = Color.Red;
    }

}

I am assuming your problem is to find the actual button again and not setting the background color. You could likewise check for the control being a button and its text being "button2" but if the text can change depending on the UI language that's probably not a good idea.

ETA: Totally forgot that you can use the control's Name property for this as well.

If you just want to change the background color of the button in a response to an event from the button you can just use the sender argument of the event handler, though.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Thanks for this one, now I know whats the use of the `Tag`. – Rye Oct 08 '10 at 07:37
  • @Rye: I'd advise you to use `Name` instead of `Tag` here as that is what you want here (also you're avoiding the problem of comparing strings and objects, then). Otherwise, the `Tag` property is just any object you want to tack onto a control you might need. If you will it can save you subclassing of controls if you just need another piece of data in a control. – Joey Oct 08 '10 at 07:42
3

You can try Control.ControlCollection.Find.

flowLayoutPanel1.Controls.Add(new Button() { Text = "button 1", Name = "btn1" });
Button btn1 = flowLayoutPanel1.Controls.Find("btn1", true).FirstOrDefault() as Button;
btn1.Text = "found!";
bla
  • 5,350
  • 3
  • 25
  • 26
  • Hm, I completely forgot the control *name*. Ouch. – Joey Oct 08 '10 at 05:33
  • @Joey Your post was correct, please post it again so I can mark it as the answer. The control name can be filtered so its fine. Thanks. – Rye Oct 08 '10 at 05:37