如何在asp.net webforms中生成5个不同的随机数



如何在文本框中生成5个不同的随机数只有1个按钮?

protected void Button1_Click(object sender, EventArgs e)
{
Random r = new Random();
int num = r.Next();      
TextBox1.Text = num.ToString();
TextBox2.Text = num.ToString();
TextBox3.Text = num.ToString();
TextBox4.Text = num.ToString();
TextBox5.Text = num.ToString();
}

我明白这样只会得到相同的数字,但是有什么方法可以得到不同的数字吗?

随机初始化的简短示例

static void Example()
{
var textBoxes = new List<TextBox> { Textbox1, Textbox2, Textbox3, Textbox4, Textbox5 };
// GUID will produce better randomization
var rand = new Random(Guid.NewGuid().GetHashCode());        
foreach (var textBox in textBoxes)
textBox.Text = rand.Next().ToString();
}

您可以像下面的示例一样将r.t next()放入循环中:

string printmsg = string.Empty;
int[] x = new int[5];
Random r = new Random();
for (int i = 0; i < 5; i++)
{
x[i] = r.Next();
printmsg += x[i] + ",";
}
lblMsg.Text = printmsg.Substring(0, printmsg.Length-1);

然后在数组或字符串或不同的文本框中使用它。

您可以将每个生成的号码添加到List中。然后检查是否包含

Random r = new Random();
var list = new List<int>(5);
for (int i = 0; i < 5; i++)
{
var num = r.Next(5);
if (!list.Contains(num)) //If not add to list 
{
list.Add(num);
}
else //If contains return back and generate again.
{
i--; 
}
}
//It will more effective if you convert this section into loop. 
Textbox1.Text = list[0].ToString();
Textbox2.Text = list[1].ToString();
Textbox3.Text = list[2].ToString();
Textbox4.Text = list[3].ToString();
Textbox5.Text = list[4].ToString();

最新更新