动态分配按钮文本通过循环 [英] Assign button text dynamically via a loop
本文介绍了动态分配按钮文本通过循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过使用如下的循环动态分配按钮控件文本:
INT ButtonNumber = 1;而(ButtonNumber小于10)
{
//什么事要做!?
ButtonNumber ++;
}
我要避免以下内容:
button1.Text =;
button2.Text =;
button3.Text =;
button4.Text =;
button5.Text =;
button6.Text =;
button7.Text =;
button8.Text =;
button9.Text =;
解决方案
理想的情况下,不具备按钮1
,按钮2
等在首位的变量。有一个集合(如列表与LT按钮>
)
私人列表<按钮和GT;按钮=新的List<按钮和GT;();
(编辑:你需要填充这个地方,当然...)
再后来更新文本:
的for(int i = 0; I< buttons.Count;我++)
{
按钮[i]。文本=我按钮+我;
}
这不与设计师发挥非常好听,很遗憾。
您的可以的获取由ID的控制,但我个人尽量不要做。如果你的真正的希望:
的for(int i = 1; I< = 10;我++)
{
控制控制=控件[键+ i];
control.Text =我按钮+我;
}
I am trying to assign button controls text dynamically by using a loop like the following:
int ButtonNumber = 1;
while (ButtonNumber < 10)
{
//WHAT TO DO HERE!?
ButtonNumber++;
}
I wanna avoid the following:
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";
解决方案
Ideally, don't have button1
, button2
etc as variables in the first place. Have a collection (e.g. a List<Button>
):
private List<Button> buttons = new List<Button>();
(EDIT: You'd need to populate this somewhere, of course...)
then to update the text later:
for (int i = 0; i < buttons.Count; i++)
{
buttons[i].Text = "I'm button " + i;
}
This doesn't play terribly nicely with the designer, unfortunately.
You can fetch a control by ID, but personally I try not to do that. If you really want to:
for (int i = 1; i <= 10; i++)
{
Control control = Controls["button" + i];
control.Text = "I'm button " + i;
}
这篇关于动态分配按钮文本通过循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文