Pass items from checkboxlist to SQL Server table

2019-08-27 18:33发布

问题:

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?

回答1:

Put the VALUES in 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());