[英]Data insert dynamically multiple rows one-button click
我想通過單擊按鈕一次來插入數據,其中有一個下拉列表選擇了數字和兩個文本框。 我選擇下拉列表編號[例如 2],並在兩個文本框中輸入數據,然后單擊一次插入按鈕。 數據保存在數據庫表中的多行中,從下拉列表中選擇多少個數字。 例如:
dropdown-list = 0,1,2,3,4; //選擇任何數字以在數據庫表中插入多行
[1] textbox =“數據”; // 輸入數據
[2] textbox =“數據”; // 輸入數據
[點擊按鈕]
我的代碼:
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次。
您僅在catch塊中關閉連接。 這就是發生的情況。 在第一個迭代中插入了值,但未關閉連接;在第二個迭代中發生了異常,並且連接已關閉。 在第三次迭代中,將再次插入值,依此類推。 這是更新的代碼
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
{
i--;
}
finally
{
con.Close();
}
}
GridView1.DataBind();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.