问题
I need help with random name picker in multiple textboxes in c# framwork. Can someone help me with how I can get started? How to think? I would appreciate the help!
回答1:
You can call Enumerable.OfType<TResult>(IEnumerable) Method to get the list of all textboxes.
And use Random Class to generate a random index.
private void btnrandompicker_Click(object sender, EventArgs e)
{
var random = new Random();
// get textboxes list
var tblist = this.Controls.OfType<TextBox>().ToList();
var randomtb = tblist[random.Next(tblist.Count)];
Console.WriteLine(randomtb.Text);
}
回答2:
I will give you an example for winforms in C# language.
List<int> numberList = new List<int>();
foreach (Control ctr in this.Controls)
{
if (ctr is TextBox)
{
GenerateRandom:
Random random = new Random();
int number = random.Next(125, 900);
var findNumber = numberList.Find(a => a == number);
if (findNumber == 0)
{
ctr.Name = "txt" + number;
numberList.Add(number);
}
else
goto GenerateRandom;
}
}
来源:https://stackoverflow.com/questions/65946553/how-can-i-do-random-name-picker-in-multiple-textboxes-in-c-sharp-framwork