将多个选定的列表框项目插入到SQL表的同一单元格中

时间:2018-08-14 14:13:05

标签: c# sql .net for-loop listbox

我想将多个列表框项目插入到SQL表中的单元格中,并以逗号分隔项目。下面发布的代码只会在列表框中添加第一个选定的项目。因此,如果您选择2或10个项目,则您选择的第一个项目将插入表格中。 for循环是我的问题,我需要获取所有选定的值。 谢谢

        protected void pg_upload_Click(object sender, EventArgs e)
        {
        using (SqlConnection mycon = new SqlConnection(connectionstring))
        {
            using (SqlCommand mycmd = mycon.CreateCommand())
            {
                if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
                }
                else
                {

                    string str = "";

                    for (int i=0; i<= listbox_software.Items.Count; i++)
                    {
                        str = listbox_software.SelectedItem.ToString();
                    }

                    mycon.Open();
                    mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
                                        "Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
                                                ", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' ,  '" + str + "')";

                    mycmd.ExecuteNonQuery();
                    PopulateGridView();

                    lblsuscessmessage.Text = "Selected Record Added";
                    lblerrormessage.Text = "";


                    textbox_make.Text = string.Empty;
                    textbox_number.Text = string.Empty;
                    textbox_asset.Text = string.Empty;
                    textbox_ip.Text = string.Empty;
                    textbox_serial.Text = string.Empty;
                    textbox_os.Text = string.Empty;
                    textbox_memory.Text = string.Empty;


                }
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

添加以下名称空间:

using System.Linq;

创建一个包含所选项目的字符串数组,然后使用string.join:

    var selection = listbox_software.SelectedItems
        .Cast<string>()
        .ToArray();
    var str = string.Join(",", selection);

答案 1 :(得分:0)

我找到了答案。

                        // To access checkbox list item's value //
                    string total = "";
                    foreach (ListItem listItem in listbox_software.Items)
                    {
                        if (listItem.Selected)
                        {
                            total =  total + "[" + listItem.Value + "][ " + " ";
                        }
                    }
                    string str = total.ToString();