我有一个文本框,当用户在文本框中输入任意数字(比如3)时,应该生成许多随机数。这是我到目前为止所做的,但它为所有3个生成相同的随机数(或者和用户输入的一样多)记录。
protected void Page_Load(object sender, EventArgs e)
{
for (Int32 x = 0; x <= 50; x++)
{
txtRandomNumber.Text = GetRandomString(x);
}
}
public string GetRandomString(int seed)
{
const string alphabet = "R";
Random rnd = new Random((seed + DateTime.Now.Millisecond));
string result = rnd.Next(10000, 99999).ToString();
string alpha = alphabet.Substring(rnd.Next(alphabet.Length - 1));
int replacementIndex = rnd.Next(0);
result = result.Remove(replacementIndex, 1).Insert(replacementIndex, alpha);
return result;
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 1; i <= int.Parse(txtNoOfPin.Text); i++)
{
if (i == 1)
{
string strConnection = ConfigurationManager.ConnectionStrings["ReliableLife"].ToString();
SqlConnection con = new SqlConnection(strConnection);
string sqlQuery = "insert into AllotPin(NoOfPin,PinNumber) values(@NoOfPin,@PinNumber)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("@NoOfPin", int.Parse(txtNoOfPin.Text));
cmd.Parameters.AddWithValue("@PinNumber", txtRandomNumber.Text);
cmd.ExecuteNonQuery();
}
else
{
string r_no = "";
for (Int32 x = 0; x <= 50; x++)
{
r_no = GetRandomString(x);
//Response.Write(GetRandomString(x) + "<br />");
}
string strConnection = ConfigurationManager.ConnectionStrings["ReliableLife"].ToString();
SqlConnection con = new SqlConnection(strConnection);
string sqlQuery = "insert into AllotPin(NoOfPin,PinNumber) values(@NoOfPin,@PinNumber)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("@NoOfPin", int.Parse(txtNoOfPin.Text));
cmd.Parameters.AddWithValue("@PinNumber", txtRandomNumber.Text);
cmd.ExecuteNonQuery();
}
}
}
请帮助,谢谢
答案 0 :(得分:0)
尝试将随机数添加到文本框
for (Int32 x = 0; x <= 50; x++)
{
txtRandomNumber.Text = x +" "+ GetRandomString(x) +" "+ txtRandomNumber.Text;
}
该程序有一些冗余,但它会根据您的要求生成随机数。
答案 1 :(得分:0)
感谢您的帮助。 我在代码的else部分解决了这个问题:
for (Int32 x = 0; x <= 50; x++)
{
r_no = GetRandomString(x);
txtRandomNumber.Text = r_no;
}
根据需要输出。