How to change the property of a control from a flowlayoutpanel?
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 woul开发者_StackOverflow中文版d I change the back color of button 2? Assuming the controls has been added at runtime.
foreach(Controls ctrl in flowlayoutpanel1.Controls)
{
//What should I put here?
}
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.
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!";
精彩评论