[英]Is it possible to modify a collection of controls in c# windows form ? How?
The C# windows form has 8 buttons. C#窗口窗体具有8个按钮。 I want to change the text of each button. 我想更改每个按钮的文本。 Those texts are random numbers without repetition. 这些文本是随机数,没有重复。 I know how to generate random numbers without repetition but I don't want write 8 instructions to assign each number to each button text respectively like this: 我知道如何不重复地生成随机数,但我不想编写8条指令来分别将每个数字分配给每个按钮文本,如下所示:
button1.Text = listNumbers[0].ToString();
button2.Text = listNumbers[1].ToString();
.
.
.
Is it possible to modify a collection of buttons in c# windows form such as using a loop? 是否可以修改c#窗口形式的按钮集合,例如使用循环? If yes, how to write these codes and their pseudocodes? 如果是,如何编写这些代码及其伪代码? Thanks. 谢谢。
You can use form's Controls collection for changing text of buttons like below. 您可以使用窗体的Controls集合来更改按钮的文本,如下所示。
foreach(var control in this.Controls)
{
if(control is Button)
{
((Button)control).Text = "New Text";
}
}
You can use LINQ's OfType<T>
with the Controls
property: 您可以将LINQ的OfType<T>
与Controls
属性一起使用:
foreach (var button in Controls.OfType<Button>()) // will only give you Buttons
{
button.Text = "some text";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.