0

I have an issue with my DropDownList which seems to be binding again on selection change and does not trigger the onSelectionChange event.

This is my aspx page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="Pest_Concern_Ltd._Default" ViewStateMode="Enabled" %>


<!DOCTYPE html>

<html lang="en">
    <head runat="server">
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <title>Pest Control Admin Dashboard</title>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />

        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

        <style>
            body {
                padding-top: 60px;
            }

            .nav-link.active {
                font-weight: bold;
                color: #0d6efd;
            }

            .header-img {
                width: 60px;
                height: 30px;
            }

            .popup-panel {
                position: fixed;
                top: 0; left: 0;
                width: 100%; height: 100%;
                background-color: rgba(0,0,0,0.5);
                z-index: 1000;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .popup-content {
                background-color: #fff;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.3);
                min-width: 300px;
                max-height: 90vh;
                overflow-y: auto; /* Enables scroll inside the form */
                border-radius: 8px;
                width: 60%;
            }

            .form-section {
                font-family: Arial;
                margin: 20px;
                max-width: 100%;
                overflow: auto;
            }

            .form-section h2 {
                text-align: center;
                text-decoration: underline;
            }

            .form-field {
                margin-top: 20px;
            }

            .row {
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                flex-wrap: nowrap; /* prevent wrapping */
                gap: 10px;
                flex: 1;
            }

            .row label, .row b {
                min-width: 70px;
                display: inline-block;
            }

            input[type="text"], .aspNetInput, select, textarea {
                padding: 5px;
                border: 1px solid #ccc;
                border-radius: 3px;
                width: 100%;
                /*max-width: 300px;*/
                box-sizing: border-box;
            }

            .checkbox-grid { 
                display: grid; 
                grid-template-columns: repeat(4, 1fr); 
                gap: 5px; 

            }

            .section-title { 
                font-weight: bold; 
                margin-top: 20px; 
            }

            .underline { 
                border-bottom: 1px solid #000; 
                display: inline-block; 
                min-width: 200px; 
            }

            .popup-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100vh;
                background-color: rgba(0, 0, 0, 0.5);
                justify-content: center;
                align-items: center;
                z-index: 9999;
                overflow: auto; /* Ensures internal scroll */
            }

            .signature-row {
                display: flex;
                justify-content: space-between;
                margin-top: 150px;
            }

            .brn-date-row {
                display: flex;
                align-items: flex-start;
                gap: 30px;               /* space between B.R.N. and date/no block */
                max-width: 600px;        /* constrain total width */
            }

            .brn-date-row > .brn-left {
                flex-shrink: 0;
                white-space: nowrap;     /* keep B.R.N. text on one line */
            }

            .brn-date-row > .date-no-right {
                display: flex;
                flex-direction: column;
                gap: 5px;
                min-width: 160px;        /* control width of date/no container */
            }

            .date-no-right {
                display: flex;
                flex-direction: column;
                gap: 5px;
                align-items:flex-start; /* ✅ this is the key line to align right */
                min-width: 160px;
            }

            .date-no-right > div {
                display: flex;
                align-items: center;
                gap: 5px;
                white-space: nowrap; /* ✅ prevents label and textbox from breaking into new line */
            }

            .error-label {
                font-weight: bold;
                margin-bottom: 10px;
                display: block;
            }
        </style>
    </head>

    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server" />

            <!-- Navigation Bar -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">
                        <img src="images/logo.png" class="header-img" alt="Logo" />
                    </a>

                    <div style ="color: #ffffff">Welcome</div> &nbsp;

                    <asp:Label ID="lblName" runat="server" Text="" ForeColor="White"></asp:Label>

                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                        <span class="navbar-toggler-icon"></span>
                    </button>

                    <div class="collapse navbar-collapse" id="navbarNav">
                        <ul class="navbar-nav ms-auto">
                            <li class="nav-item"><a class="nav-link" href="#quotations">Quotations</a></li>
                            <li class="nav-item"><a class="nav-link" href="#invoices">Invoices</a></li>
                            <li class="nav-item"><a class="nav-link" href="#interventions">Interventions</a></li>
                            <li class="nav-item"><a class="nav-link" href="#clients">Clients</a></li>
                            <li class="nav-item"><a class="nav-link" href="#users">Users</a></li>
                        </ul>
                    </div>
                </div>
            </nav>

            <!-- Main Container -->
            <div class="container">
                <asp:Label ID="lblError" runat="server" ForeColor="Red" Visible="False" CssClass="error-label"></asp:Label>

                <!-- Quotations -->
                <section id="quotations">
                    <h2>Quotations</h2>

                    <asp:Button ID="btnIssueQuotation" runat="server" Text="Issue New Quotation" CssClass="btn btn-primary mt-3 mb-3" OnClientClick="showNewQuotation(); return false;" />

                    <!-- Filter Controls -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <asp:TextBox ID="txtQuotationNo" runat="server" CssClass="form-control" Placeholder="Quotation #" />
                        </div>

                        <div class="col-md-4">
                            <asp:TextBox ID="txtCustomerName" runat="server" CssClass="form-control" Placeholder="Customer Name" />
                        </div>
                    </div>

                    <asp:GridView ID="gvQuotations" runat="server" CssClass="table table-bordered" />
                </section>

                <!-- Invoices -->
                <section id="invoices">
                    <h2>Invoices & Payments</h2>

                    <asp:Button ID="btnNewInvoice" runat="server" Text="Create Invoice" CssClass="btn btn-success mt-3 mb-3" />

                    <br />

                    <!-- Filter Controls -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <asp:TextBox ID="txtInvoiceNo" runat="server" CssClass="form-control" Placeholder="Invoice #" />
                        </div>

                        <div class="col-md-4">
                            <asp:TextBox ID="txtCustomerName2" runat="server" CssClass="form-control" Placeholder="Customer Name" />
                        </div>
                    </div>

                    <asp:GridView ID="gvInvoices" runat="server" CssClass="table table-bordered" />
                </section>

                <!-- Interventions -->
                <section id="interventions">
                    <h2>Interventions</h2>

                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <asp:TextBox ID="txtinterventionReportNo" runat="server" CssClass="form-control" Placeholder="Intervention Report #" />
                        </div>

                        <div class="col-md-6 mb-3">
                            <asp:TextBox ID="txtCustomerName3" runat="server" CssClass="form-control" Placeholder="Customer Name" />
                        </div>

                        <div class="col-md-6 mb-3">
                            <asp:TextBox ID="txtFilterDate" runat="server" TextMode="Date" CssClass="form-control" />
                        </div>

                        <div class="col-md-6 mb-3">
                            <asp:DropDownList ID="ddlFilterLocation" runat="server"  CssClass="form-control">
                                <asp:ListItem Text = "Location" Value = "Location" Selected=  "True"></asp:ListItem>
                            </asp:DropDownList>
                        </div>
                    </div>

                    <asp:GridView ID="gvInterventions" runat="server" CssClass="table table-bordered" />
                </section>

                <!-- Client Management -->
                <section id="clients">
                    <h2>Client Management</h2>

                    <!-- Filter Controls -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <asp:TextBox ID="txtCustomerName4" runat="server" CssClass="form-control mb-3" Placeholder="Customer Name" />
                        </div>
                    </div>

                    <asp:GridView ID="gvCustomers" runat="server" CssClass="table table-bordered" />
                </section>

                <!-- User Management -->
                <section id="users">
                    <h2>User Management</h2>

                    <!-- Filter Controls -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <asp:TextBox ID="txtUser" runat="server" CssClass="form-control mb-3" Placeholder="User Name" />
                        </div>
                    </div>

                    <asp:GridView ID="gvUsers" runat="server" CssClass="table table-bordered" />
                </section>
            </div>

            <!-- Popup Panel -->
            <asp:Panel ID="pnlPopup" runat="server" CssClass="popup-panel" style="display:none;">
                <div class="popup-content">
                    <div class="form-section">
                        <h2>QUOTATION FORM</h2>

                        <div class="row brn-date-row">
                            <div class="brn-left">
                                <b>B.R.N.:</b> 

                                <asp:Label ID="lblBRN" runat="server" Text="C14121936"></asp:Label>
                            </div>

                            <div class="date-no-right">
                                <div>
                                    <b>Date:</b>
                                    <asp:Label ID="lblDate" runat="server" Width="100px" />
                                </div>

                                <div>
                                    <b>No.:</b>

                                    <asp:Label ID="lblQuotation" runat="server" Width="100px" />
                                </div>
                            </div>
                        </div>

                        <asp:UpdatePanel ID="updPopup" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <div class="form-field">
                                    <table width="100%">
                                        <tr>
                                            <td width="10%">
                                                <b>Customer :</b>
                                            </td>

                                            <td>
                                                <asp:DropDownList ID="ddlCustomer" runat="server" CssClass="searchable-dropdown" Width="100%" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged" />
                                            </td>
                                        </tr>

                                        <tr>
                                            <td>
                                                <b>Address :</b>
                                            </td>

                                            <td>
                                                <asp:TextBox ID="txtAddress" runat="server" CssClass="input" Enabled="false" />
                                            </td>
                                        </tr>

                                        <tr>
                                            <td>
                                                <b>Tel. :</b>
                                            </td>

                                            <td>
                                                <asp:TextBox ID="txtTel" runat="server" CssClass="input" Enabled="false" />
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </ContentTemplate>

                            <Triggers>
                                <asp:AsyncPostBackTrigger ControlID="ddlCustomer" EventName="SelectedIndexChanged" />
                            </Triggers>
                        </asp:UpdatePanel>

                        <div class="section-title">SERVICES PROVIDED</div>

                        <div class="checkbox-grid">
                            <asp:CheckBox ID="chkRodents" Text="Rodents" runat="server" />
                            <asp:CheckBox ID="chkAnts" Text="Ants" runat="server" />
                            <asp:CheckBox ID="chkFlies" Text="Flies" runat="server" />
                            <asp:CheckBox ID="chkFleas" Text="Fleas" runat="server" />

                            <asp:CheckBox ID="chkCockroaches" Text="Cockroaches" runat="server" />
                            <asp:CheckBox ID="chkTermites" Text="Termites" runat="server" />
                            <asp:CheckBox ID="chkWasps" Text="Wasps" runat="server" />
                            <asp:CheckBox ID="chkMosquitoes" Text="Mosquitoes" runat="server" />

                            <asp:CheckBox ID="chkBirdControl" Text="Bird Control" runat="server" />
                            <asp:CheckBox ID="chkSpiders" Text="Spiders" runat="server" />
                            <asp:CheckBox ID="chkLizard" Text="Lizard" runat="server" />
                            <asp:CheckBox ID="chkOthers" Text="Others" runat="server" />
                        </div>

                        <div class="checkbox-grid" style="margin-top: 10px;">
                            <asp:CheckBox ID="chkInterior" Text="Interior Perimeter" runat="server" />
                            <asp:CheckBox ID="chkExterior" Text="Exterior Perimeter" runat="server" />
                            <asp:CheckBox ID="chkOneOff" Text="1 Off Treatment" runat="server" />
                        </div>

                        <div class="form-field">
                            Following our visit at your premises we are pleased to offer our best quotation for the chosen treatment:
                        </div>

                        <div class="form-field">
                            Total Amount: Mur (Rs.) 
                            
                            <asp:TextBox ID="txtAmount" runat="server" Style="max-width: 300px;" />

                            &nbsp; for 12 visits per year.
                        </div>

                        <div class="form-field"><i>In case of infestation – (free of charge)</i></div>
                        <div class="form-field"><b>Full payment upon acceptance</b></div>

                        <div class="section-title">TERMITE TREATMENTS</div>

                        <div class="form-field">
                            <asp:CheckBox ID="chkProofing" runat="server" Text="1. Termite Proofing - Soil treatment with chemical or structural barriers (Drilling)" /><br />
                            <asp:CheckBox ID="chkBaiting" runat="server" Text="2. Termite Baiting" /><br />
                            <asp:CheckBox ID="chkFumigation" runat="server" Text="3. Termite Fumigation" /><br />
                            <asp:CheckBox ID="chkPreConstruction" runat="server" Text="4. Pre-Construction Anti-Termite Treatment" /><br />
                            <asp:CheckBox ID="chkPostConstruction" runat="server" Text="5. Post-Construction Anti-Termite Treatment" />
                        </div>

                        <div class="form-field">
                            Total Amount (Rs.): <asp:TextBox ID="txtTermiteAmount" runat="server" Style="max-width: 300px;" />
                            &nbsp;&nbsp;
                            5 Years <asp:CheckBox ID="chk5Years" runat="server" />
                            &nbsp;&nbsp;
                            10 Years <asp:CheckBox ID="chk10Years" runat="server" />
                        </div>

                        <div class="form-field"><b>Full payment upon acceptance</b></div>

                        <div class="form-field"><b>Guarantee over 5 and 10 years will be given depending on the treatment.</b></div>

                        <div class="form-field">
                            Shall you need additional information, do not hesitate to contact us.
                            We thank you again for the trust you have put in our company.
                        </div>

                        <div class="signature-row">
                            <div><i>For Pest Concern Ltd</i></div>
                            <div><i>Customer's Signature</i></div>
                        </div>
                    </div>

                    <%--<asp:Button ID="btnSubmit" runat="server" Text="Submit" />--%>
                    <input type="button" value="Close" onclick="hideNewQuotation()" />
                </div>
            </asp:Panel>
        </form>

        <!-- Scripts -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

        <script type="text/javascript">
            function showNewQuotation() {
                document.getElementById('<%= pnlPopup.ClientID %>').style.display = 'flex';
            }

            function hideNewQuotation() {
                document.getElementById('<%= pnlPopup.ClientID %>').style.display = 'none';
            }
        </script>

        <script>
            $(document).ready(function () {
                $('.searchable-dropdown').select2();
            });
        </script>

        <script>
            Sys.Application.add_load(function () {
                $('#<%= ddlCustomer.ClientID %>').select2();
            });
        </script>
    </body>
</html>

And this my aspx.vb page:

Imports System.Data.SqlClient

Public Class _Default
    Inherits System.Web.UI.Page

    Dim myError As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim role As String = ""
        Dim dt As DataTable

        If Not IsPostBack Then
            If Session("Role") Is Nothing Then
                FormsAuthentication.SignOut()

                Response.Redirect("Login.aspx", False)

                Context.ApplicationInstance.CompleteRequest()

                Return
            End If

            If User.Identity.IsAuthenticated Then
                If User.IsInRole("Owner") Then
                    role = "Owner"
                ElseIf User.IsInRole("Manager") Then
                    role = "Manager"
                ElseIf User.IsInRole("Technician") Then
                    role = "Technician"
                End If

                ' Show/hide UI sections based on roles
                gvQuotations.Visible = (role = "Manager" Or role = "Owner")
                btnIssueQuotation.Visible = (role = "Manager" Or role = "Owner")

                gvInvoices.Visible = (role = "Owner")
                btnNewInvoice.Visible = (role = "Owner")

                gvCustomers.Visible = (role = "Owner")
                gvUsers.Visible = (role = "Owner")

                ' Interventions: Technicians and Owners
                gvInterventions.Visible = (role = "Technician" Or role = "Owner")
                txtFilterDate.Visible = (role = "Technician" Or role = "Owner")
                ddlFilterLocation.Visible = (role = "Technician" Or role = "Owner")

                lblName.Text = Session("Username")
            End If

            dt = getCustomers()

            ViewState("Customers") = dt

            If myError <> "" Then
                lblError.Text = myError
                lblError.Visible = True

                myError = ""

                Exit Sub
            End If

            ddlCustomer.DataSource = dt
            ddlCustomer.DataTextField = "Name"
            ddlCustomer.DataValueField = "ID"
            ddlCustomer.DataBind()

            ddlCustomer.Items.Insert(0, New ListItem("-- Select Customer --", ""))
        Else
            lblError.Visible = False

            dt = CType(ViewState("Customers"), DataTable)
        End If

        lblDate.Text = Format(Now, "dd-MMM-yyyy")
    End Sub

    Public Sub ddlCustomers_SelectedIndexChanged(sender As Object, e As EventArgs)
        MsgBox("1")

        Try
            Dim selectedID As Integer = Convert.ToInt32(ddlCustomer.SelectedValue)
            Dim dt As DataTable = CType(ViewState("Customers"), DataTable)
            Dim selectedRow = dt.AsEnumerable().FirstOrDefault(Function(r) Convert.ToInt32(r("ID")) = selectedID)

            If selectedRow IsNot Nothing Then
                txtAddress.Text = selectedRow("Address").ToString()
                txtTel.Text = selectedRow("Phone").ToString()
            End If
        Catch ex As Exception
            lblError.Text = myError
            lblError.Visible = True

            myError = ""
        End Try
    End Sub

    Protected Function getCustomers() As DataTable
        Dim conn As SqlConnection
        Dim da As SqlDataAdapter = Nothing
        Dim dt As New DataTable
        Dim cmd As String = ""

        conn = New SqlConnection(ConfigurationManager.ConnectionStrings("PestControlDB").ConnectionString)

        Try
            conn.Open()

            cmd = ""
            cmd = cmd & "SELECT ID                                                              " & vbCrLf
            cmd = cmd & ", (CustFName + ' ' + CustLName) as 'Name'                              " & vbCrLf
            cmd = cmd & ", (CustHouseNum + ', ' + CustAddr1 + ', ' + CustCity) AS 'Address'     " & vbCrLf
            cmd = cmd & ", (CustPhone + '/' + CustMobile) AS 'Phone'                            " & vbCrLf
            cmd = cmd & "FROM tblCustomer                                                       " & vbCrLf
            cmd = cmd & "ORDER BY CustFName, CustLName                                          " & vbCrLf

            da = New SqlDataAdapter(cmd, conn)
            da.Fill(dt)

            conn.Close()
        Catch ex As Exception
            myError = ex.Message
        End Try

        Return dt
    End Function
End Class

Can anyone please help and tell me what I am doing wrong?

Tried binding the DropDownList on every postback and then only on first page load. Tried removing AutoPostBack on my DropDownList....this enabled me to now successfully change the value but the onSelectionChange event is not triggered still.

1 Answer 1

1

Well, leaving out the HUGE BIG MASSIVE elephant in the room?

Your question is the following:

I have a drop down in a update panel. I'm also using the 3rd party JavaScript library called ".select()" to change how the drop down list works.

Also, keep in mind that the .select() library has to run when the page renders. However, you have the .select() code working against a DDL inside of a update panel. So, on first page load, the .select() system should work. However, if you have any page-post back, and especially a partial page post back (from the Update panel), then the page on-ready does NOT fire, and does not run. As a result, your .select() library code to select the drop down list and set up the dropdown list? That code does NOT run when you post-back the update panel. What this means is that you need the .select() library code to run WHEN the update panel is rendered.

So, you need to add the following code to trigger + run the .select() library code when the update panel code runs. Hence this:

            <script>
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.add_endRequest(runafterup);

                function runafterup() {

                     $('#<%= ddlCustomer.ClientID %>').select2();
                }


            </script>

So, the above will do the "same thing" as your current code you have like this:

        <script>
            $(document).ready(function () {
                $('.searchable-dropdown').select2();
                $('#<%= ddlCustomer.ClientID %>').select2();
                
            });
        </script>

So, I would actually build a separate test page, and 100%, 200% make sure you .select2() code works, and then (and only then) would I re-introduce the .select2() code into your existing page.

And I see no mention that you have a custom DDL, and I see no mention that you using that 3rd party .select2() library that is clearly messing around with your DDL.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. To start with, my select2() is working fine. But, i've also tried removing it from my page completely and it my selected value in my dropdownlist still resets after a selectedindexchange and still selectedindexchange event is never trigerred
The ddl should not re-set unless you re-binding. Are you 100% sure the selected index event is not firing? Also, you are persisting the table for the ddl in viewstate, which means on each post-back, that table is traveling from client side to server - you probably should use session, or better yet, query the database based on PK id to get Address + phone. The performance increase of not using viewstate will FAR FAR outweigh the cost in terms of persisting that table in viewstate. I would put a debug-print in the on selected index changed event. The select2() needs to run after upda
Thanks for all your help Albert D. Kallal. I finally found the issue. In my database I forgot to add the auto-increment to the primary key of the tblCustomer table. As a result, the ID field for all my records were empty. However, I don't understand why this was causing this issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.