Insert (Save) Multiselect DropDownList value in Database in ASP.Net using C# and VB.Net

Last Reply 28 days ago By dharmendr

Posted 28 days ago

Hello, 

I understand how i can use select2 plugin in ASP.Net but what i do not understand is how to get all the value selected and store them into a sql database table. 

I look at this example, but i still do not get it. 

https://www.aspforums.net/Threads/132523/Get-selected-items-of-multiselect-DropDownList-using-jQuery-Select2-Plugin-in-ASPNet/

I have a Dropdownlist that display data from a db and i have a Textbox field to allow user to imput new item that does not appear in the Dropdownlist. what I am trying to do is if someone select items or wirte the item on the textbox fiel, the items will be stored into a new table. 

As of my code, nothing fency,

can someone please advise? 

thanks

<asp:DropDownList ID="ddl1" Width="100%" runat="server" multiple="multiple" CssClass="form-control js-example-placeholder-single"
    ToolTip="Select" DataSourceID="blablabla" DataValueField="Keyword" DataTextField="Keyword" AppendDataBoundItems="true" >
</asp:DropDownList>
<asp:TextBox ID ="Keyword_enter" runat="server" AutoPostBack="true" Width="100%" >
<asp:Button ID="btnSave" Text="Save " runat="server" OnClick="btnSave_Click" />

 

        protected void btnSave_Click(object sender, EventArgs e)
        {           
            Conn3.Open();      
            sqlCom.Parameters.Add(new SqlParameter("@Keyword", ddl1.SelectedValue));            
            sqlCom.ExecuteNonQuery();
            if (Keyword_enter.Text.Contains(','))
            {
                string[] arrayval = Keyword_enter.Text.Trim().Split(',');
                int j = arrayval.Length;
                int i = 0;
                for (i = 0; i < j; i++)
                {
                    sqlCom.Parameters.Clear();
                    sqlCom.Parameters.AddWithValue("@Keyword", arrayval[i]);
                    sqlCom.ExecuteNonQuery();
                }
                Lit2.Text = "recorded ";
                Keyword_enter.Text = String.Empty;
            }
            else
            {
                Lit2.Text = "Single value entered";
                sqlCom.Parameters.Add(new SqlParameter("@Keyword", Keyword_enter.Text));
                sqlCom.ExecuteNonQuery();
                Keyword_enter.Text = String.Empty;
            }    

 

You are viewing reply posted by: dharmendr 28 days ago.
Posted 28 days ago

HiBmChrist,

Refer the below modified code.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $(".js-example-placeholder-single").select2({
            placeholder: "Select",
            allowClear: false
        });
        $('#ddl1').on('change', function () {
            $('#<%=hfSelected.ClientID%>').val($(this).val());
        });
    });
</script>
<asp:DropDownList ID="ddl1" Width="300px" runat="server" multiple="multiple" CssClass="form-control js-example-placeholder-single"
    ToolTip="Select ">
</asp:DropDownList>
<asp:HiddenField ID="hfSelected" runat="server" />
<asp:TextBox ID="Keyword_enter" runat="server" Width="100%"></asp:TextBox>
<asp:Button ID="btnSave" Text="Save " runat="server" OnClick="btnSave_Click" />
<asp:Literal ID="Lit2" runat="server" />

C#

protected void btnSave_Click(object sender, EventArgs e)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection Conn3 = new SqlConnection(conString);
    SqlCommand sqlCom = new SqlCommand("INSERT INTO Keyword VALUES(@Keyword)", Conn3);
    Conn3.Open();
    string keyWords = Keyword_enter.Text.Trim() + "," + hfSelected.Value;
    string[] arrayval = keyWords.Trim().Split(',');
    for (int i = 0; i < arrayval.Length; i++)
    {
        if (!string.IsNullOrEmpty(arrayval[i]))
        {
            sqlCom.Parameters.Clear();
            sqlCom.Parameters.AddWithValue("@Keyword", arrayval[i]);
            sqlCom.ExecuteNonQuery();
            Lit2.Text = "recorded ";
        }
        Keyword_enter.Text = String.Empty;
    }
    ddl1.SelectedIndex = -1;
    hfSelected.Value = "";
    Conn3.Close();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        PopulateDropDownList()
    End If
End Sub

Private Sub PopulateDropDownList()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT DISTINCT Country FROM Customers WHERE Country IS NOT NULL"
    Dim cmd As SqlCommand = New SqlCommand(query)
    Using con As SqlConnection = New SqlConnection(conString)
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using ds As DataSet = New DataSet()
                sda.Fill(ds)
                ddl1.DataSource = ds
                ddl1.DataTextField = "Country"
                ddl1.DataValueField = "Country"
                ddl1.DataBind()
            End Using
        End Using
    End Using
End Sub

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim Conn3 As SqlConnection = New SqlConnection(conString)
    Dim sqlCom As SqlCommand = New SqlCommand("INSERT INTO Keyword VALUES(@Keyword)", Conn3)
    Conn3.Open()
    Dim keyWords As String = Keyword_enter.Text.Trim() & "," + hfSelected.Value
    Dim arrayval As String() = keyWords.Trim().Split(","c)
    For i As Integer = 0 To arrayval.Length - 1
        If Not String.IsNullOrEmpty(arrayval(i)) Then
            sqlCom.Parameters.Clear()
            sqlCom.Parameters.AddWithValue("@Keyword", arrayval(i))
            sqlCom.ExecuteNonQuery()
            Lit2.Text = "recorded "
        End If
        Keyword_enter.Text = String.Empty
    Next
    ddl1.SelectedIndex = -1
    hfSelected.Value = ""
    Conn3.Close()
End Sub

Screenshot

The Form

Record After Insert in DataBase