Reputation: 135
I have this code:
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();
}
}
After I insert in those 5 TextBxes values in the table I only get the value from the first one. Can anyone tell me what's wrong here?
Upvotes: 1
Views: 1212
Reputation: 141588
In your try
you are using Response.Redirect("User6.aspx");
.
Response.Redirect
will abort the thread (all code stops executing), which gets call right after the first insertion into the database.
Instead, you want to do the redirect after your 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");
One last thing. Your code doesn't appear to be cleaning up resources. You should be putting your SqlCommand and SqlConnection in a using
statement.
Upvotes: 5