[英]loop through textboxes c#
我有5個文本框,我想遍歷它們並獲取每個文本框值,並將其插入到單獨行中的表中。 我怎樣才能做到這一點? 我嘗試過這樣的事情:
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());
}
您可能的意思是:
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns.Text +"',@cnp,@data,'5')", con);
代替:
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns +"',@cnp,@data,'5')", con);
由於您無法將string
和TextBox
連接在一起,因為它是一個對象,其字段之一是Text
,其中包含輸入到其中的文本。
注意:謹防SQL注入攻擊,請不要這樣做,而應使用cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
返回已注釋掉的解決方案cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
。 再次確保輸入raspuns.Text
。
假設問題是此行的錯誤:
//cmd.Parameters.AddWithValue("@raspuns", raspuns);
更改為:
cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.