gpt4 book ai didi

c# - 更改在运行时添加的控件的属性

转载 作者:行者123 更新时间:2023-11-30 15:48:23 24 4
gpt4 key购买 nike

我有一个表单,其中几个按钮在运行时通过“for”方法添加

 public Form()
{
for (int i = 0 ... )
Button b = new Button()
b.text = (string) i ;
etc..
etc..
}

.现在我想在某个事件上更改按钮的文本属性。如何做到这一点?我尝试了一些方法,但都没有用。因为按钮变量在方法内部,所以它们在外部不可用。

谢谢

最佳答案

变量并不重要(尽管您可以将它们存储在单个 List<T> 字段中,如果它使事情变得更容易的话)。执行此操作的正常方法是查看 Controls集合(如有必要,递归)。

foreach(Control control in someParent.Controls) {
Button btn = control as Button;
if(btn != null) {
btn.Text = "hello world";
// etc
}
}

上面假设所有按钮都被添加到同一个父控件;如果不是这种情况,则递归地走:

void DoSomething(Control parent) {
foreach(Control control in parent.Controls) {
Button btn = control as Button;
if(btn != null) {
btn.Text = "hello world";
// etc
}
DoSometing(control); // recurse
}
}

关于c# - 更改在运行时添加的控件的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2661492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com