将多个复选框列表值插入到 sql db asp.net C#

Insert multiple checkboxlist values to sql db asp.net C#

我正在尝试使用 ASP.NET C# 将多个 INT 类型的 CheckBoxList 值插入 SQL 数据库。我在我的代码中设置了一个断点并且循环工作但是一旦它获得第一个选定的值,它就会保持该值并导致主键约束。最后,它只是插入一个值。经过几天的研究,我所有的发现都展示了如何将多个字符串插入到 SQL 数据库,但 none 用于 INT。非常感谢任何帮助。

    for (int i = 0; i < cbAvailableEntities.Items.Count - 1; i++)
{
    SqlConnection con = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand("InsertProjectEntity", con);

        using(con)
        {
            con.Open();
            using(cmd)
            {
                 if (cbAvailableEntities.Items[i].Selected)
                 {
                     //This code gets the Project ID that is to be associated with the new info
                     DALSectionAccessData LastProjectID = new DALSectionAccessData(connString);
                     //This puts the Project ID needed into the variable _pID
                     int _pID = LastProjectID.GetLastLogReportID();
                     cmd.CommandType = CommandType.StoredProcedure;
                     nr.Entities = cbAvailableEntities.SelectedValue;
                     cmd.Parameters.AddWithValue("@ProjectID", _pID);
                     cmd.Parameters.AddWithValue("@CorpID", nr.Entities);
                     cmd.ExecuteNonQuery();
                  }
            }
        }
}

错误是这么说的

Server Error in '/' Application.

Violation of PRIMARY KEY constraint 'PK_ProjectEntity'. Cannot insert duplicate key in object 'dbo.ProjectEntity'. The statement has been terminated.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_ProjectEntity'. Cannot insert duplicate key in object 'dbo.ProjectEntity'. The statement has been terminated.

在你的循环中,你正在检查 if() 语句以查看是否选择了 Item[i],但是如果是,你没有对 Item[i] 做任何事情来区分一次迭代和另一次迭代下一个。因此,您 运行 为复选框列表中的每个选定项目使用完全相同的代码,而不是为每个项目做不同的事情。

尝试改变这个:

cmd.Parameters.AddWithValue("@CorpID", nr.Entities);

像这样:

cmd.Parameters.AddWithValue("@CorpID", cbAvailableEntities.Items[i].Value);