none
How to store multiselect values in database with comma seperation RRS feed

  • Question

  • I am using a multiselect plugin which converts the listbox into multiselect dropdownlist with checkbox and i want to store the selected values in database by seperating them with comma like option1,option2.

    <div class="col-md-4 col-12">
       <div class="form-group">
          <label for="bkgenres">Genres</label>
          <asp:UpdatePanel runat="server">
             <ContentTemplate>
                <script type="text/javascript">
                   function pageLoad() {
                       document.multiselect('#bkgenres');
                       document.multiselect('#bkgenres').deselectAll();
                   };
                </script>
                <asp:ListBox ID="bkgenres" runat="server" CssClass="form-control multiselect-wrapper" multiple="multiple" onChange="mydun()"></asp:ListBox>
             </ContentTemplate>
             <Triggers>
                <asp:AsyncPostBackTrigger ControlID="bktype" EventName="SelectedIndexChanged" />
             </Triggers>
          </asp:UpdatePanel>
       </div>


    I am using the listbox inside updatepanel and its working all fine but when i select multiple items and try to store in database only first selected option gets selected. This is my cs code: 

                String get_value = "";
                for (int i = 0; i < bkgenres.Items.Count; i++)
                {
                    if (bkgenres.Items[i].Selected)
                    {
                        get_value = get_value + bkgenres.Items[i].Text + ",";
                    }
                }
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "insert into Books (bookname,bookauthor,bookpublisher,bookdesc,bookdate,bookedition,bookpages,booktype,bookgenre,booklanguage) values (@bkname,@bkauthor,@bkpublication,@bkdesc,@bkdate,@bkedition,@bkpages,@bktype,@bkgenres,@bklang)";
    
                cmd.Parameters.AddWithValue("@bkname", bkname.Text);
                cmd.Parameters.AddWithValue("@bkauthor", bkauthor.Text);
                cmd.Parameters.AddWithValue("@bkpublication", bkpublication.Text);
                cmd.Parameters.AddWithValue("@bkdesc", bkdesc.Text);
                cmd.Parameters.AddWithValue("@bkdate", bkrdate.Text);
                cmd.Parameters.AddWithValue("@bkedition", bkedition.Text);
                cmd.Parameters.AddWithValue("@bkpages", bkpages.Text);
                cmd.Parameters.AddWithValue("@bkgenres", get_value);
                cmd.Parameters.AddWithValue("@bktype", bktype.SelectedItem.ToString());
                cmd.Parameters.AddWithValue("@bklang", bklanguages.Text);
                cmd.ExecuteNonQuery();

    I after adding the data i am getting out in database table is like this option1,

    Please a little help will be good.

    Monday, February 3, 2020 3:52 PM

Answers