如何从 flowlayoutpanel 更改控件的属性?

发布于 2024-09-26 18:41:15 字数 290 浏览 3 评论 0原文

假设以编程方式添加控件并假设每个控件的名称相同,如何更改 flowlayoutpanel 中控件的属性?

例如,此图像显示有 2 个文本框和两个按钮, 如何更改按钮 2 的背景颜色?假设控件已在运行时添加。

替代文字

foreach(Controls ctrl in flowlayoutpanel1.Controls)
{
//What should I put here?
}

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?
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初懵 2024-10-03 18:41:15

那么,最简​​单的方法是保留对您要添加的按钮的显式引用。否则,您可以添加一个标签来区分它们(以抵御 i18n 问题)。例如,您可以将“button2”的标签设置为“button2”,然后您可以使用:

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

}

我假设您的问题是再次找到实际的按钮而不是设置背景颜色。您同样可以检查该控件是否为按钮且其文本是否为“button2”,但如果文本可以根据 UI 语言进行更改,则可能不是一个好主意。

预计到达时间:完全忘记了您也可以使用控件的Name 属性来实现此目的。

如果您只想更改按钮的背景颜色以响应按钮中的事件,则只需使用事件处理程序的 sender 参数即可。

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.

羞稚 2024-10-03 18:41:15

您可以尝试 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!";

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!";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文