1
好的。幾天前,我問了一個問題,如何在不使用數組的情況下生成100,1000,10000等隨機數字,並且我的問題被刪除了,因爲可能答案並不那麼明顯。我用簡單的解決方案得到了這一點,但現在我有另一個問題。我在這裏嘗試的是用不同的隨機數填充每個動態創建的標籤。我不知道每10行總是有什麼原因得到相同的數字。這裏是代碼背後,我試圖讓工作:用隨機數填充動態創建的控件
protected void btnExample1Random_Click(object sender, EventArgs e)
{
//Making the controls visible
this.Master.FindControl("Div1").Visible = true;
//Generating the random numbers
for (int i = 0; i < 10; i++)
{
Label randomTask = new Label();
Label emptyTask = new Label();
TextBox userInputTextBox = new TextBox();
Random rnd = new Random();
int caseInt = rnd.Next(1, 4), myNum = 0;
switch (caseInt)
{
case 1:
caseInt = 100;
myNum = rnd.Next(1, 100);
break;
case 2:
caseInt = 1000;
myNum = rnd.Next(1, 1000);
break;
case 3:
caseInt = 10000;
myNum = rnd.Next(1, 10000);
break;
}
//Forming the controls
randomTask.ID = "lbl" + i.ToString();
randomTask.Text = caseInt.ToString() + " - " + myNum.ToString() + " ";
userInputTextBox.ID = "box" + i.ToString();
emptyTask.ID = "check" + i.ToString();
//Adding the controls into the placeholder
phTutorijal1.Controls.Add(randomTask);
phTutorijal1.Controls.Add(userInputTextBox);
phTutorijal1.Controls.Add(emptyTask);
phTutorijal1.Controls.Add(new LiteralControl("<br />"));
}
//Separating the next created controls into new line
phTutorijal1.Controls.Add(new LiteralControl("<br />"));
}
這個代碼中有一個錯誤,我找不到它。生成佔位符的每10行都使用相同的數字。我在這裏錯過了什麼?
更新:邁克爾·劉發現在我的錯誤是:我需要把外面的Random rnd = new Random();
爲週期
在'for'循環之前(外部)移動'Random rnd = new Random();' – 2013-02-25 22:20:22
Aaaaah,謝謝邁克爾,沒有看到:) – al1en 2013-02-25 22:21:44