I'm trying to take items from a checkboxlist and add them to a SQL Server table. I assumed it would be as easy as looping through each item and then inserting it into the table, but I'm getting an unhandled exception with the following code:
我正在尝试从复选框列表中获取项目并将它们添加到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();
}
}
Edit: one of the suggestions below worked, but it's putting in the ID of the item rather than the value of the list item itself. How can I insert the value for each item in the list into the SQL table?
编辑:以下建议之一工作,但它是放入项目的ID而不是列表项本身的值。如何将列表中每个项的值插入SQL表?
1 个解决方案
#1
5
Put the VALUES
in paranthesis:
把VALUES放在paranthesis中:
"INSERT INTO Boxes (BoxNumber) VALUES (@selected)";
Also, i assume you have to replace
另外,我假设你必须更换
for (int i = 0; i <= UPCList.Items.Count; i++)
with
同
for (int i = 0; i < UPCList.Items.Count; i++)
and you might want to insert the item's text instead of the index:
并且您可能希望插入项目的文本而不是索引:
command.Parameters.AddWithValue("@selected", listBox.Items[i].ToString());
#1
5
Put the VALUES
in paranthesis:
把VALUES放在paranthesis中:
"INSERT INTO Boxes (BoxNumber) VALUES (@selected)";
Also, i assume you have to replace
另外,我假设你必须更换
for (int i = 0; i <= UPCList.Items.Count; i++)
with
同
for (int i = 0; i < UPCList.Items.Count; i++)
and you might want to insert the item's text instead of the index:
并且您可能希望插入项目的文本而不是索引:
command.Parameters.AddWithValue("@selected", listBox.Items[i].ToString());