views:

37

answers:

2

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?
}
+2  A: 

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
@Joey Thanks for this one, now I know whats the use of the `Tag`.
Rye
@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
+2  A: 

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!";
Lee Sy En
Hm, I completely forgot the control *name*. Ouch.
Joey
@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