我是C#的新手。我创建了一个随机类,设法生成一些不那么随机的数字。但我的问题是我想将这些数字输出到6个不同的文本框。我敢肯定,有一种更有效的方法可以做到这一点,也不会长篇大论。 这就是我做到的:
protected void genBtn_Click(object sender, EventArgs e)
{
Random RandomClass = new Random();
int num1 , num2, num3 , num4, num5 , num6;
num1 = RandomClass.Next(1,49);
num2 = RandomClass.Next(1,49);
num3 = RandomClass.Next(1,49);
num4 = RandomClass.Next(1,49);
num5 = RandomClass.Next(1,49);
num6 = RandomClass.Next(1,49);
TextBox1.Text = num1.ToString();
TextBox2.Text = num2.ToString();
TextBox3.Text = num3.ToString();
TextBox4.Text = num4.ToString();
TextBox5.Text = num5.ToString();
TextBox6.Text = num6.ToString();
答案 0 :(得分:2)
创建一个数组,然后循环?
Random RandomClass = new Random();
Control[] textboxes = new Contro[] {TextBox1,TextBox2,TextBox3,TextBox4,TextBox5,TextBox6};
foreach(Control c in textboxes)
c.Text = RandomClass.Next(1,49).ToString();
或List<TextBox>
然后ForEach
?
List<TextBox> textboxes = new List<TextBox>() {TextBox1,TextBox2,TextBox3,TextBox4,TextBox5,TextBox6};
textboxes.ForEach(x => x.Text = RandomClass.Next(1,49).ToString());
答案 1 :(得分:0)
您的示例有效,但您不需要所有这些额外的变量。
protected void genBtn_Click(object sender, EventArgs e)
{
Random RandomClass = new Random();
TextBox1.Text = RandomClass.Next(1,49).ToString();
TextBox2.Text = RandomClass.Next(1,49).ToString();
TextBox3.Text = RandomClass.Next(1,49).ToString();
TextBox4.Text = RandomClass.Next(1,49).ToString();
TextBox5.Text = RandomClass.Next(1,49).ToString();
TextBox6.Text = RandomClass.Next(1,49).ToString();
}
答案 2 :(得分:0)
你可以这样做:
protected void genBtn_Click(object sender, EventArgs e)
{
Random RandomClass = new Random();
TextBox1.Text = RandomClass.Next(1, 49).ToString();
TextBox2.Text = RandomClass.Next(1,49).ToString();
TextBox3.Text = RandomClass.Next(1,49).ToString();
TextBox4.Text = RandomClass.Next(1,49).ToString();
TextBox5.Text = RandomClass.Next(1,49).ToString();
TextBox6.Text = RandomClass.Next(1,49).ToString();
}
答案 3 :(得分:0)
您可以在不同的面板控件上放置文本框,并且可能有更多文本框。这样做:
// Name your random num text boxes with some convention, like txtRand1. But not the others
// Recursive func to read all text boxes
private void RecFillRandTextBoxes(Control parent, rand)
{
foreach (Control c in parentcontrols)
{
if (typeof(c) is TextBox && c.Name.StartsWith("txtRand"))
c.Text = Next(1,49).ToString();
else
RecFillRandTextBoxes(c, rand);
}
}
然后只需在genBtn_Click
RecFillRandTextBoxes(this, rand);