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

← PrevNext →

There is virtually a race going on to design new Plug-ins to outsmart their predecessors. While seaching new plug-ins, 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 select drop-down lists with huge cache of data.

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

Must Read: How to Use jQuery Select2 with JSON Array Data for Multiple Selection

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, we will 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

Before you start, you must download the Select2 library and save it in a folder in your computer. The library has the necessary .js and .css files that we'll need to include in our web page.

Add the source of the .js file and the .css link inside the <head> tag along the jQuery CDN.

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    
    <script src="select2-3.4.1/select2.js"></script>
    <link href="select2-3.4.1/select2.css" rel="stylesheet"/>
</head>

Now, let us see Markup and the CodeBehind procedures.

The MarkUp
<!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>
    
    <script src="select2-3.4.1/select2.js"></script>
    <link href="select2-3.4.1/select2.css" rel="stylesheet"/>
</head>
<body>
    <form id="form1" runat="server">
        <%--THE SELECT DROP-LIST WITH NO DEFAULT VALUES (OPTIONS)--%>
        <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>
Code Behind (C#)
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();

        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 Books";
                con.Open();

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

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

                // FOR MULTIPLE SELECTION. SET THE VALUE AS FALSE, AND SEE WHAT HAPPENS.
                Books.Multiple = true;
            }
        }
    }
}
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()

                ' FOR MULTIPLE SELECTION. SET THE VALUE AS FALSE, AND SEE WHAT HAPPENS.
                Books.Multiple = True
            End Using
        End Using
    End Sub
End Class

If you have noticed, we do not have to bother about styling the controls on the webpage. Select2 automatically takes over the look and feel and the all important search part and all we are left with is populating the list with the necessary data using the code behind procedures.

More Features

This Plug-in has another nice and interesting feature. The Select2 will allow 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, as it will force the user 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. Also it reduces the need for space on the website.

← PreviousNext →