2012-01-27 77 views
0

我有5個文本框,我想遍歷它們並獲取每個文本框的值並將其插入到一個單獨的行中的表中。我怎樣才能做到這一點?我想是這樣的:循環通過文本框c#

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()); 
} 
+5

您應該將SQLConnection代碼移到循環外部 – 2012-01-27 14:06:50

+0

您可以使用George的解決方案,但我可以建議您將SqlConnection代碼移到循環外部。 – Raj 2012-01-27 14:07:49

+3

我喜歡你所控制的兩個值是如何參數化的,並且容易被注入的值在查詢 – John 2012-01-27 14:10:19

回答

1

假設的問題是這一行的錯誤:

//cmd.Parameters.AddWithValue("@raspuns", raspuns); 

將其更改爲:

cmd.Parameters.AddWithValue("@raspuns", raspuns.Text); 
2

你大概的意思是:

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); 

正如你不能連接stringTextBox,因爲它是一個對象,其一個領域是Text其中包含了文本輸入到它。

注意:注意SQL注入攻擊,不要這樣做,而應該使用cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);來解決註釋掉的解決方案。再次確保把raspuns.Text

+0

啊,是的,我錯過了另外一個提到'raspuns'的好消息。 – asawyer 2012-01-27 14:10:44

+0

我只能得到第一個文本框的值。可以給你一個解決方案嗎? – user1147188 2012-01-27 14:38:18

+0

@ user1147188您的意思是「我只獲得第一個文本框的值」是什麼意思?是唯一存儲的第一個嗎?或者你得到空串爲其他人?或者你有一些錯誤?請更具體一些。 – Krizz 2012-01-27 17:36:48