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:
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?
Put the
VALUES
in paranthesis:Also, i assume you have to replace
with
and you might want to insert the item's text instead of the index: