且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您好,我如何将从复选框列表中选择的多个项目插入到数据库中

更新时间:2023-10-08 11:27:34

您好,您可以使用如下所示的代码检索所选值
Hello you can use code something like shown below to retrieve the selected values
string[] items = new string[list_box.SelectedItems.Count()];
for (int idx = 0; idx < list_box.SelectedItems.Count; idx++) {
    items[idx] = list_box.SelectedItems[idx];
}


您可以使用会员9332883555 给出的代码。

you也可以尝试这个查询部分。



You can use the code what Member 9332883555 is given.
you can try this query part too.

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO stuhob(StuID,HobID) VALUES (@StuID,@HobID)";
cmd.Parameters.AddWithValue("@StuID",txtStuID.Text);
cmd.Parameters.AddWithValue("@HobID",chHobbies.Items[i].Text );
cmd.ExecuteNonQuery();


如果您的数据库表只有一行和一列,您需要存储所选的值,您可以使用for循环来获取用户选择的值并使用分隔符作为逗号或任何其他特殊字符并将值保存在字符串中并将其作为参数传递给存储过程,但是如果每个都有单行或单列根据您的需要,您可以使用解决方案1 ​​来插入/更新复选框的值。
If your database table has only a single row and single column where you need to store the selected values you can use for loop to get selected values by user and use a delimiter as comma or any other special character and hold the values in a string and pass it as a parameter to your stored procedure ,but in case you have single row or single column for each values of your checkbox then you can go with solution 1 to insert/update as per your needs.