2013-07-19 45 views
0

我試圖從複選框列表中將項目添加到SQL Server表中。我認爲這將是通過每個項目循環,然後將其插入到表很容易,但我得到一個未處理的異常與下面的代碼:將項目從複選框列表傳遞到SQL Server表

using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    for (int i = 0; i <= UPCList.Items.Count; i++) 
    { 
     string finalSubmit = 
       "INSERT INTO Boxes (BoxNumber)" 
       + "VALUES @selected"; 

      SqlCommand command = new SqlCommand(finalSubmit, connection); 
      command.Parameters.AddWithValue("@selected", i); 
      command.Connection.Open(); 
      command.ExecuteNonQuery(); 
      command.Connection.Close(); 
     } 
} 

編輯:下面工作的建議之一,但它將放入項目的ID而不是列表項本身的值。如何將列表中每個項目的值插入到SQL表格中?

+0

什麼是例外? –

+0

如果你想知道確切的錯誤,我會建議將你的代碼包裝在for循環中,圍繞'try {} catch {}' – MethodMan

+0

這不是特定的。只是說不知道。 –

回答

5

VALUES在paranthesis:

"INSERT INTO Boxes (BoxNumber) VALUES (@selected)"; 

而且,我想你必須更換

for (int i = 0; i <= UPCList.Items.Count; i++) 

for (int i = 0; i < UPCList.Items.Count; i++) 

,你可能要插入的項目的文本而不是的指數:

command.Parameters.AddWithValue("@selected", listBox.Items[i].ToString()); 
+0

這工作,但現在它只是將ID放入表中而不是列表項值。我該怎麼做呢? –

+0

你的ListBox的數據源是什麼?嘗試'command.Parameters.AddWithValue(「@ selected」,listBox1.Items [i] .ToString());' –

+0

我沒有,並且工作!但是,它將兩次添加項目,就好像它將兩次重複列表一樣。 我對編程相當陌生,所以我很抱歉,如果這是我錯過了一些明顯的東西。 –

相關問題