将项目从复选框列表传递到SQL Server表 [英] Pass items from checkboxlist to SQL Server table

查看:82
本文介绍了将项目从复选框列表传递到SQL Server表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从复选框列表中提取项目并将其添加到SQL Server表中。我认为这就像遍历每个项目然后将其插入表一样简单,但是我收到了一个未处理的异常,其代码如下:

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

编辑:以下建议之一可行,但建议输入项目ID,而不是列表项目本身的值。如何将列表中每个项目的值插入SQL表?

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?

推荐答案

放入放在括号中:

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

这篇关于将项目从复选框列表传递到SQL Server表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆