我有这段代码:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
TextBox[] rasp = new TextBox[] { textbox1, textbox2, textbox3, textbox4, textbox5 };
foreach (TextBox raspuns in rasp)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'5')", con);
cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("User6.aspx");
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex);
}
finally
{
con.Close();
}
}
在表格中插入5个TextBxes值后,我只从第一个中获取值。谁能告诉我这里有什么问题?
答案 0 :(得分:5)
在您使用的try
Response.Redirect("User6.aspx");
。
Response.Redirect
将中止线程(所有代码停止执行),在第一次插入数据库后立即调用。
相反,您希望在foreach
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
TextBox[] rasp = new TextBox[] { textbox1, textbox2, textbox3, textbox4, textbox5 };
foreach (TextBox raspuns in rasp)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'5')", con);
cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex);
}
finally
{
con.Close();
}
}
Response.Redirect("User6.aspx");
最后一件事。您的代码似乎没有清理资源。您应该将您的SqlCommand和SqlConnection放在using
语句中。