How to do Multiple selections using jQuery Select2 using Asp.Net C# and Vb.Net

← PrevNext →

Last updated: 30th August 2024

There is virtually a race going on to design new Plug-ins to outsmart their predecessors. While seaching the internet, I came across Select2, a jQuery plug-in that will change the way dropdown controls will look and function. This plug-in looks very promising when it comes to designing and implementing a SELECT drop-down lists with a relative large dataset.

➡️ If you haven’t heard about it, then I recommend you first read about Select2 control.

➡️ I have used this plug-in my projects and I have found it useful.

See this demo

What it says it does, particularly connecting with a remote data source and displaying the results with infinite scrolls, course if you have infinite list of data like the one Google has.

We have used DropDownList, CheckBoxList and HTML <select> element numerous times to design our websites and applications and they have really helped us to fulfill our task. Select2 changes the way we select multiple values from a drop down list.

Here in this article, I'll show you how to use the HTML <select> element to create a Multiple Selection, Auto Searchable drop-down list with the help of jQuery Select2 plug-in. The select drop-down list will be populated using data fetched from a remote SQL server database table.

Select2 jQuery Plug-in

Using Select2 using CDN

First, you must include Select2 CDN (content delivery network) within the <head></head> tags inside your web page.

<head>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>

Now, let us see the entire Markup and the Code-behind procedures (both C# and Visual Basic code).

The MarkUp

I have added a SELECT dropdown list control in my web page. The SELECT element will be populated with data extracted from an SQL Server table named books.

The SELECT element is then attached to the Select2 plug-in. See the jQuery code inside the <script> tag.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Select2 Plug-in</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <%--the select element with no values. it will be populated using code behind procedures--%>
        <div>
            <select id="Books" style="width:300px" runat="server"></select>
        </div>
    </form>
</body>
<script>
    $(document).ready(function() {
        $("#Books").select2({ placeholder: 'Find and Select Books' });
    });
</script>
</html>
See this demo
Code Behind (C#)

The code behind procedure is to connect to an SQL Server database, extract data from a table named "dbo.books" and populate the SELECT element with list of books.

➡️ Scroll down for VB code.

using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack){ BindData(); }
    }
    private void BindData()
    {
        DataTable dt = new DataTable();

        // the connect string.
        using (SqlConnection con = new SqlConnection("Data Source=DNA;" +
            "Persist Security Info=False;" +
            "Initial Catalog=DNA_CLASSIFIED;" + 
            "User Id=sa;Password=demo;Connect Timeout=30;"))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = "SELECT BookName FROM dbo.Books";
                con.Open();

                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand= cmd;
                sda.Fill(dt);

                // bind select element with database table.
                Books.DataSource = dt; Books.DataValueField = "BookName";
                Books.DataBind();

                Books.Multiple = true;  // set value "true" for multiple selection.
            }
        }
    }
}
Vb.Net
Option Explicit On
Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
            Handles form1.Load
        If Not IsPostBack Then
            Me.BindData()
        End If
    End Sub

    Private Sub BindData()
        Dim dt As DataTable = New DataTable
        Using con As SqlConnection = New SqlConnection("Data Source=DNA;" & _
            "Persist Security Info=False;" & _
            "Initial Catalog=DNA_CLASSIFIED;" & _
            "User Id=sa;Password=demo;Connect Timeout=30;")

            Dim strQuery As String = "SELECT BookName FROM Books"

            Using cmd As SqlCommand = New SqlCommand(strQuery)
                Dim sda As SqlDataAdapter = New SqlDataAdapter

                cmd.Connection = con : con.Open()
                sda.SelectCommand = cmd
                sda.Fill(dt)

                ' BIND THE SELECT DROP-DOWN LIST WITH A DATABASE TABLE.
                Books.DataSource = dt : Books.DataValueField = "BookName"
                Books.DataBind()

                Books.Multiple = True   ' set value "true" for multiple selection.
            End Using
        End Using
    End Sub
End Class

🚀 You don't have to bother about styling the controls on the webpage (at design time). Select2 will automatically apply necessary styles for look and feel and the all "important" search feature.

More Features

This Plug-in has another nice and interesting feature. "Select2" allows us to set a minimum input value, which will help filter the result from a huge list of data in a remote database. This improves the efficiency of the drop-down list, since it allows users to enter minimum required characters, before it actually begins the search.

<script>
    $(document).ready(function() {
        $("#Books").select2({
            placeholder: 'Find and Select Books',
            minimumInputLength: 3
        });
    });
</script>

It's worth trying this Plug-in if you want to make your multiple selection drop-down list or an Auto Complete box, simple and appealing.

See this demo

← PreviousNext →