I have 5 text-boxes and I want to loop over them and get each text-box value and insert it into a table on a separate row. How can I do that? I tried something like this:
TextBox[] rasp = new TextBox[] { textbox1, textBox2, textBox3,
textBox4, textBox5 };
foreach (TextBox raspuns in rasp) {
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
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);
cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
}
You probably meant:
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns.Text +"',@cnp,@data,'5')", con);
instead of:
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns +"',@cnp,@data,'5')", con);
As you cannot concatenate string
and TextBox
as it is an object whose one of fields is Text
which contains the text entered into it.
Note: Beware of SQL injection attacks, don't do this this way, instead resort back to your commented out solution with cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
. Again, make sure to put raspuns.Text
.
Assuming the problem is an error with this line:
//cmd.Parameters.AddWithValue("@raspuns", raspuns);
Change it to:
cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.