我想通过单击按钮一次插入数据,其中有一个下拉列表选择数字和两个文本框 . 我选择下拉列表编号[例如2]并在两个文本框中输入数据然后单击插入按钮一次 . 数据在数据库表中保存多行,从下拉列表中选择多少个数字 . 例如-
dropdown-list = 0,1,2,3,4; //选择任意数字以在数据库表中插入多行
[1] textbox = "data"; // 输入数据
[2] textbox = "data"; // 输入数据
[按钮点击]
我的代码:
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string value = DropDownList4.SelectedValue.ToString(); // Get the dropdown value
int count = 0;
int.TryParse(value, out count); // cast the value to integer
for (int i = 0; i < count; i++) // iterate it for the N times
{
SqlCommand insert = new SqlCommand("insert into Test(Name, Username) values(@Name, @Username)", con);
insert.Parameters.AddWithValue("@Name", TextBox1.Text);
insert.Parameters.AddWithValue("@Username", TextBox2.Text);
try
{
con.Open();
insert.ExecuteNonQuery();
}
catch
{
con.Close();
}
}
GridView1.DataBind();
}
- 此代码无法在数据库中正确插入数据 . 当我选择dropdwn-list值3时,行插入2次 . 当选择5时,插入3次 . 什么是需要改变请帮助 . 日Thnx
1 回答
您只在catch块中关闭连接 . 这就是发生的事情 . 在第一次迭代中插入值但连接未关闭,在第二次迭代中发生异常并且连接已关闭 . 在第3次迭代中,再次插入值,依此类推 . 这是更新的代码