AutoComplete cascading ListBoxes with multiple selections using jQuery Select2 Plugin in ASP.Net

Last Reply 11 months ago By pandeyism

Posted 11 months ago

Adding Update panel to autocomplete cascading listboxes with multiple selection using the javascript not to work.

When I remove the update panel it works but it is taking so long to load.

Also the datetimepicker not working with select and multiselect functionality added to the page which used to work earlier.

Please help.

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
  $( function() {
      $( '[id*=txtDate]' ).datepicker();
  } );
</script>
    <script type="text/javascript">
        $(function () {
            $('[id*=ddlCountries]').select2({
                placeholder: "Select",
                allowClear: true
            });
            $('[id*=ddlStates]').select2({
                placeholder: "Select",
                allowClear: true
            });
            $('[id*=ddlCities]').select2({
                placeholder: "Select",
                allowClear: true
            });
        });
    </script>

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        Country:
                <asp:ListBox ID="ddlCountries" runat="server" AutoPostBack = "true" OnSelectedIndexChanged = "Country_Changed" >
                </asp:ListBox><br/><br/>
                State:
                    <asp:ListBox ID="ddlStates" runat="server" AutoPostBack = "true" OnSelectedIndexChanged = "State_Changed" SelectionMode="Multiple">
                    </asp:ListBox><br/><br/>
                City:               
                    <asp:ListBox ID="ddlCities" runat="server" SelectionMode="Multiple">
                    </asp:ListBox>             
    </ContentTemplate>
</asp:UpdatePanel>
<br/><br/><asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<br/><br/><asp:Button Text="Submit" runat="server"></asp:Button>

 

Private Sub BindListBox(ddl As ListBox, query As String, text As String, value As String, defaultText As String)
    Dim conString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
    Dim cmd As New SqlCommand(query)
    Using con As New SqlConnection(conString)
        Using sda As New SqlDataAdapter()
            cmd.Connection = con
            con.Open()
            ddl.DataSource = cmd.ExecuteReader()
            ddl.DataTextField = text
            ddl.DataValueField = value
            ddl.DataBind()
            con.Close()
        End Using
    End Using
    ddl.Items.Insert(0, New ListItem(defaultText, "0"))
End Sub


Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim query As String = "select CountryId, CountryName from Countries"
        BindListBox(ddlCountries, query, "CountryName", "CountryId", "Select Country")
        ddlStates.Enabled = False
        ddlCities.Enabled = False
        ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
        ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    End If
End Sub

Protected Sub Country_Changed(sender As Object, e As EventArgs)
    ddlStates.Enabled = False
    ddlCities.Enabled = False
    ddlStates.Items.Clear()
    ddlCities.Items.Clear()
    ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim countryId As Integer = Integer.Parse(ddlCountries.SelectedItem.Value)
    If countryId > 0 Then
        Dim query As String = String.Format("select StateId, StateName from States where CountryId = {0}", countryId)
        BindListBox(ddlStates, query, "StateName", "StateId", "Select State")
        ddlStates.Enabled = True
    End If
End Sub


Protected Sub State_Changed(sender As Object, e As EventArgs)
    ddlCities.Enabled = False
    ddlCities.Items.Clear()
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim stateId As Integer = Integer.Parse(ddlStates.SelectedItem.Value)
    If stateId > 0 Then
        Dim query As String = String.Format("select CityId, CityName from Cities where StateId = {0}", stateId)
        BindListBox(ddlCities, query, "CityName", "CityId", "Select City")
        ddlCities.Enabled = True
    End If
End Sub

Protected Sub Submit(sender As Object, e As EventArgs)
    Dim message As String = ""
    For Each item As ListItem In ddlState.Items
        If item.Selected Then
            message += item.Value
        End If     
    Next  
End Sub

 

You are viewing reply posted by: pandeyism 11 months ago.
Posted 11 months ago

Hi swathiyemp,

Refer below sample.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css"
    rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"
    type="text/javascript"></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 () {
        $('[id*=txtDate]').multiDatesPicker({
            dateFormat: 'dd/mm/yy'
        });
    });
</script>
<script type="text/javascript">
    $(function () {
        selectlistBox();
    });
    function selectlistBox() {
        $('[id*=ddlCountries]').select2({
            placeholder: "Select",
            allowClear: true
        });
        $('[id*=ddlStates]').select2({
            placeholder: "Select",
            allowClear: true
        });
        $('[id*=ddlCities]').select2({
            placeholder: "Select",
            allowClear: true
        });
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (prm != null) {
        prm.add_endRequest(function (sender, e) {
            if (sender._postBackSettings.panelsToUpdate != null) {
                selectlistBox();
            }
        });
    };
</script>
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            Country:
            <asp:ListBox ID="ddlCountries" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Country_Changed"
                SelectionMode="Multiple"></asp:ListBox><br /><br />
            State:
            <asp:ListBox ID="ddlStates" runat="server" AutoPostBack="true" OnSelectedIndexChanged="State_Changed"
                SelectionMode="Multiple"></asp:ListBox><br /><br />
            City:
            <asp:ListBox ID="ddlCities" runat="server" SelectionMode="Multiple"></asp:ListBox>
        </ContentTemplate>
    </asp:UpdatePanel><br /><br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox><br /><br />
    <asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit"></asp:Button>
</div>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient

Code

C#

private void BindListBox(ListBox ddl, string query, string text, string value, string defaultText)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            ddl.DataSource = cmd.ExecuteReader();
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
            con.Close();
        }
    }
    ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select CountryId, CountryName from Countries";
        BindListBox(ddlCountries, query, "CountryName", "CountryId", "Select Country");
        ddlStates.Enabled = false;
        ddlCities.Enabled = false;
        ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
        ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    }
}

protected void Country_Changed(object sender, EventArgs e)
{
    ddlStates.Enabled = false;
    ddlCities.Enabled = false;
    ddlStates.Items.Clear();
    ddlCities.Items.Clear();
    ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
    ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    string selectedCountry = "";
    int selectedCount = 0;
    foreach (ListItem item in ddlCountries.Items)
    {
        if (item.Selected)
        {
            selectedCount++;
            selectedCountry += item.Value + ",";
        }
    }
    if (selectedCount > 0)
    {
        string query = string.Format("select StateId, StateName from States where CountryId IN ({0})", selectedCountry.TrimEnd(','));
        BindListBox(ddlStates, query, "StateName", "StateId", "Select State");
        ddlStates.Enabled = true;
    }
}

protected void State_Changed(object sender, EventArgs e)
{
    ddlCities.Enabled = false;
    ddlCities.Items.Clear();
    ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
    string selectedState = "";
    int selectedCount = 0;
    foreach (ListItem item in ddlStates.Items)
    {
        if (item.Selected)
        {
            selectedCount++;
            selectedState += item.Value + ",";
        }
    }
    if (selectedCount > 0)
    {
        string query = string.Format("select CityId, CityName from Cities where StateId IN ({0})", selectedState.TrimEnd(','));
        BindListBox(ddlCities, query, "CityName", "CityId", "Select City");
        ddlCities.Enabled = true;
    }
}

protected void Submit(object sender, EventArgs e)
{
    string message = "";
    foreach (ListItem item in ddlCountries.Items)
    {
        if (item.Selected)
        {
            message += item.Text + " " + item.Value + "\\n";
        }
    }
    foreach (ListItem item in ddlStates.Items)
    {
        if (item.Selected)
        {
            message += item.Text + " " + item.Value + "\\n";
        }
    }
    foreach (ListItem item in ddlCities.Items)
    {
        if (item.Selected)
        {
            message += item.Text + " " + item.Value + "\\n";
        }
    }
    string date = txtDate.Text;
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "Date is  : " + date + "');", true);
}

VB.Net

Private Sub BindListBox(ByVal ddl As ListBox, ByVal query As String, ByVal text As String, ByVal value As String, ByVal defaultText As String)
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim cmd As SqlCommand = New SqlCommand(query)
    Using con As SqlConnection = New SqlConnection(conString)
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            con.Open()
            ddl.DataSource = cmd.ExecuteReader()
            ddl.DataTextField = text
            ddl.DataValueField = value
            ddl.DataBind()
            con.Close()
        End Using
    End Using

    ddl.Items.Insert(0, New ListItem(defaultText, "0"))
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim query As String = "select CountryId, CountryName from Countries"
        BindListBox(ddlCountries, query, "CountryName", "CountryId", "Select Country")
        ddlStates.Enabled = False
        ddlCities.Enabled = False
        ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
        ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    End If
End Sub

Protected Sub Country_Changed(ByVal sender As Object, ByVal e As EventArgs)
    ddlStates.Enabled = False
    ddlCities.Enabled = False
    ddlStates.Items.Clear()
    ddlCities.Items.Clear()
    ddlStates.Items.Insert(0, New ListItem("Select State", "0"))
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim selectedCountry As String = ""
    Dim selectedCount As Integer = 0
    For Each item As ListItem In ddlCountries.Items
        If item.Selected Then
            selectedCount += 1
            selectedCountry += item.Value & ","
        End If
    Next
    If selectedCount > 0 Then
        Dim query As String = String.Format("select StateId, StateName from States where CountryId IN ({0})", selectedCountry.TrimEnd(","c))
        BindListBox(ddlStates, query, "StateName", "StateId", "Select State")
        ddlStates.Enabled = True
    End If
End Sub

Protected Sub State_Changed(ByVal sender As Object, ByVal e As EventArgs)
    ddlCities.Enabled = False
    ddlCities.Items.Clear()
    ddlCities.Items.Insert(0, New ListItem("Select City", "0"))
    Dim selectedState As String = ""
    Dim selectedCount As Integer = 0
    For Each item As ListItem In ddlStates.Items
        If item.Selected Then
            selectedCount += 1
            selectedState += item.Value & ","
        End If
    Next

    If selectedCount > 0 Then
        Dim query As String = String.Format("select CityId, CityName from Cities where StateId IN ({0})", selectedState.TrimEnd(","c))
        BindListBox(ddlCities, query, "CityName", "CityId", "Select City")
        ddlCities.Enabled = True
    End If
End Sub

Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
    Dim message As String = ""

    For Each item As ListItem In ddlCountries.Items
        If item.Selected Then
            message += item.Text & " " + item.Value & "\n"
        End If
    Next
    For Each item As ListItem In ddlStates.Items

        If item.Selected Then
            message += item.Text & " " + item.Value & "\n"
        End If
    Next
    For Each item As ListItem In ddlCities.Items
        If item.Selected Then
            message += item.Text & " " + item.Value & "\n"
        End If
    Next

    Dim date1 As String = txtDate.Text
    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('" & message & "Date is  : " & date1 & "');", True)
End Sub

Screenshot