随机选择Windows窗体控件

时间:2016-12-22 00:04:04

标签: c# .net winforms

我正在尝试创建一个程序,我有81个文本框。我需要能够以编程方式在c#中选择Windows窗体控件,并将其设置为某个字符串,并更改它是否为只读并更改背景颜色。有没有人对如何做到这一点有任何想法?像这样:

RandomTextbox.Text = MyStringValue;
RandomTextbox.ReadOnly = true;
RandomTextbox.BackColor = System.Drawing.SystemColors.Window;

3 个答案:

答案 0 :(得分:3)

如果所有文本框都属于同一个父控件,则可以执行以下操作:

var random = new Random();  // Put this somewhere to be called one time

var textboxes = parentControl.Controls.OfType<TextBox>().ToList();
var randomTextbox = textboxes[random.Next(textboxes.Count)];

randomTextbox.Text = "I've been choooooooosen!";

答案 1 :(得分:2)

将TextBox命名为TextBox1,TextBox2,...,TextBox81

// generates a random value between 1 and 81
Random rnd = new Random();

// find the textbox and change its properties
TextBox tb = this.Controls.Find("TextBox" + rnd.Next(1, 81).ToString(), true).FirstOrDefault() as TextBox;
if (tb != null)
    // change color, text, ect

答案 2 :(得分:0)

找到表单上TextBox的所有控件:

var boxes = this.Controls.Cast<Control>().Where( x => x.GetType() == typeof( TextBox ) )
   .Cast<TextBox>().ToList();

从上面找到的列表中选择一个随机的并对其执行某些操作。这里代码将Text属性设置为Random Text

Random r = new Random();
int random = r.Next( boxes.Count() - 1);
boxes[ random ].Text = "Random Text";