I am trying to make a program, and I have 81 textboxes. I need to be able to programmatically select a Windows Form Control in c#, and set it's text to be a certain string, and to change whether it is readonly and change background color. Does anyone have any ideas on how to do this? Like this:
RandomTextbox.Text = MyStringValue;
RandomTextbox.ReadOnly = true;
RandomTextbox.BackColor = System.Drawing.SystemColors.Window;
If all of the textboxes belong to the same parent control, you can do something like this:
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!";
Name your TextBox's as 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
Find all the controls on your form which are TextBox
:
var boxes = this.Controls.Cast<Control>().Where( x => x.GetType() == typeof( TextBox ) )
.Cast<TextBox>().ToList();
Select a random one from the found list above and do something to it. Here the code sets the Text
property to Random Text
:
Random r = new Random();
int random = r.Next( boxes.Count() - 1);
boxes[ random ].Text = "Random Text";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.