Cannot have multiple items selected in a DropDownList but debugger steps through code perfectly

18,350

Solution 1

Input from Cory made me decide to go back and check that every DropDownList had only 1 selection specified and that's when I found the problem.

In getReservation() above:

        ' GET DRIVER
        ' -------------------------------------------------------------
        If dr("driverid") = "0" Then
            ' Self Drive
            rblTrips.Items(1).Selected = True

            pnlDriven.Visible = False
            pnlSelfDriven.Visible = True

        Else
            ' Driven
            rblTrips.Items(0).Selected = True

            pnlSelfDriven.Visible = False
            pnlDriven.Visible = True

            ddlDriver.ClearSelection()
            ddlDriver.Items.FindByValue(dr("driverid")).Selected = True
        End If

And then later:

        ' GET VEHICLES
        ' -------------------------------------------------------------
        ddlVehicle.ClearSelection()
        ddlDriver.Items.FindByValue(dr("vehicleid")).Selected = True

This was just bad copy/paste, so for people viewing this answer, make 100% sure that you're only selecting ONCE

As a side note, I'm told that the following is better practice:

' Do this:
ddlVehicles.SelectedValue = dr("vehicleid")

' Instead of this:
ddlVehicles.Items.FindByValue(dr("vehicleid").Selected = True

Solution 2

While any ListControl is being rendered, a flag is set if it encounters more than one selected item. If the flag is true, the abstract method VerifyMultiSelect is called. DropDownList's implementation of VerifyMultiSelect throws an exception if it encounters multiple selected items, so the only possible reason you're seeing this exception is because you have multiple ListItems with Selected set to true within one of your DropDownLists.

I would carefully examine the results of your SQL to determine if there's a case where more than one item in the same DropDownList is having its Selected property set to true. There are three lines of code in the getReservation() function in your sample above that alter this property.

Perhaps it's the way you handle IsPostBack. There's a previously selected item stored in ViewState for that control, and you're trying to select another value along with it after post-back.

EDIT: OP found a solution.

Solution 3

I had a similar issue when reworking someone elses old code. For me it was a view state issue that was addressed simply by calling

myDropDown.ClearSelection(); 

They were pulling the datasource for the dropdown from an enum without a key and thus using FindText to make a selection. If the dropdown selected item was changed however they re-ran the statement on PostBack with the FindText without first calling

myDropDown.ClearSelection();

which as per Corys reply meant two items - the one just selected plus the one already selected in viewstate - were now selected and an exception was therefore thrown.

Not sure how it ever worked but it wasn't exposed until some minor change was made to code. So if anyone is struggling to find duplicate lines of code as per OPs answer, then you might also want to consider view state mechanics on post back.

Share:
18,350
Ortund
Author by

Ortund

I started teaching myself code around 2003 out of a high school computer course I was doing as a part of my curriculum. Very quickly I became filled with a sense of pride as I saw that the code I was writing was creating things so I decided to pursue this as a career. I had a few jobs developing software over the next 10 years during which time I'd learned a lot and developed my skills considerably. In 2013, however, I found myself without a job in an economic climate that didn't favor my prospects for re-employment. I had to find a way to make money fast. Having started my own software development business at that time, I managed to keep my head above water for a few years. In 2017 however, after a few personal setbacks, I decided to go back to the job market. I've since been working for a small software house where I develop and maintain solutions and bespoke data management systems for our clients on a regular basis. Most of these use ASP.NET Web Forms, but as I'm the only employee on staff with experience in MVC, I'm tasked with updating and maintaining all of our MVC properties as well.

Updated on June 05, 2022

Comments

  • Ortund
    Ortund almost 2 years

    The subject error appears when I refresh the page (databinding is done on page load). Stepping through the page's code reveals no errors and no page is referenced in the stack trace:

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
    
    Source Error: 
    
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    
    Stack Trace:
    [HttpException (0x80004005): Cannot have multiple items selected in a DropDownList.]
       System.Web.UI.WebControls.DropDownList.VerifyMultiSelect() +106
       System.Web.UI.WebControls.ListControl.RenderContents(HtmlTextWriter writer) +161
       System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
       System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +10
       System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
       System.Web.UI.Control.Render(HtmlTextWriter writer) +10
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.UpdatePanel.RenderChildren(HtmlTextWriter writer) +256
       System.Web.UI.UpdatePanel.Render(HtmlTextWriter writer) +37
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
       System.Web.UI.Control.Render(HtmlTextWriter writer) +10
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +173
       System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
       System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
       System.Web.UI.Control.Render(HtmlTextWriter writer) +10
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
       System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
       System.Web.UI.Page.Render(HtmlTextWriter writer) +29
       System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
       System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060
    

    When last this happened, I had this image tag on the master page:

    <img src="<%=Page.ResoveUrl("~/Images/footerLogo.png") %>" />
    

    Modifying this to remove the <% %> (<img src="/Images/footerLogo.png" />) block fixed the error, but I don't have any such tags on the master page this time (or any page that links to the page in question). Here's my code:

    Imports MySql.Data
    Imports MySql.Data.MySqlClient
    
    Partial Class maintreservation
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Not IsPostBack Then
    
                getClients()
                getDrivers()
                getVehicles()
    
                pnlDriven.Visible = False
                pnlSelfDriven.Visible = False
    
                If Not String.IsNullOrEmpty(Session("resid")) AndAlso Session("resid") IsNot Nothing Then
    
                    getReservation()
    
                End If
    
            End If
        End Sub
    
        Protected Sub getDrivers()
            ddlDriver.ClearSelection()
    
            Dim db As New Database
    
            Dim sql As String = "select driverid, drivername from drivers order by drivername"
    
            Dim dr As MySqlDataReader = db.GetReader(sql)
    
            If dr.Read Then
    
                ddlDriver.DataSource = dr
                ddlDriver.DataTextField = "drivername"
                ddlDriver.DataValueField = "driverid"
                ddlDriver.DataBind()
    
            End If
            dr.Close()
    
            ddlDriver.Items.Insert(0, New ListItem("Select a Driver", 0))
        End Sub
    
        Protected Sub getVehicles()
            ddlVehicle.ClearSelection()
    
            Dim db As New Database
    
            Dim sql As String = "select veh.vehicleid, veh.licence_plate, veh.model, vm.make from vehicles veh " & _
                "inner join vehicle_manufacturers vm on veh.make = vm.makeid order by veh.make"
    
            Dim dr As MySqlDataReader = db.GetReader(sql)
    
            While dr.Read
    
                ddlVehicle.Items.Add(New ListItem(dr("make") & " " & dr("model") & " " & " (" & dr("licence_plate") & ")", dr("vehicleid")))
            End While
            dr.Close()
    
            ddlVehicle.Items.Insert(0, New ListItem("Select a Vehicle", 0))
        End Sub
    
        Protected Sub getClients()
            ddlClient.ClearSelection()
    
            Dim db As New Database
    
            Dim sql As String = "select clientid, clientname, contact from clients order by clientname"
    
            Dim dr As MySqlDataReader = db.GetReader(sql)
    
            If dr.Read Then
    
                ddlClient.DataSource = dr
                ddlClient.DataTextField = "clientname"
                ddlClient.DataValueField = "clientid"
                ddlClient.DataBind()
    
            End If
            dr.Close()
    
            ddlClient.Items.Insert(0, New ListItem("Select an Agent", 0))
            getClientContact()
        End Sub
    
        Protected Sub getClientContact()
    
            Dim db As New Database
    
            Dim sql As String = "select contact, vat_no from clients where clientid = " & ddlClient.SelectedItem.Value
    
            Dim dr As MySqlDataReader = db.GetReader(sql)
    
            If dr.Read Then
    
                If Not IsDBNull(dr("contact")) Then
                    lblClientContact.Text = dr("contact")
                Else
                    lblClientContact.Text = ""
                End If
                If Not IsDBNull(dr("vat_no")) Then
                    txtVatNo.Text = dr("vat_no")
                Else
                    txtVatNo.Text = ""
                End If
            End If
            dr.Close()
        End Sub
    
        Protected Sub ddlClient_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlClient.SelectedIndexChanged
    
            getClientContact()
    
        End Sub
    
        Protected Sub getReservation()
    
            Dim db As New Database
    
            Dim sql As String = _
                "select * from reservations res " & _
                "inner join reservationbody trip on res.reservationid = trip.reservationid " & _
                "inner join vehicles vehicle on trip.vehicleid = vehicle.vehicleid " & _
                "left outer join drivers driver on trip.driverid = driver.driverid " & _
                "where res.reservationid = " & Session("resid")
    
            Dim dr As MySqlDataReader = db.GetReader(sql)
    
            If dr.Read Then
    
                ' GET CLIENT
                ' -------------------------------------------------------------
                ddlClient.ClearSelection()
                ddlClient.Items.FindByValue(dr("clientid")).Selected = True
                getClientContact()
    
                ' GET VOUCHER
                ' -------------------------------------------------------------
                If IsDBNull("vouchernumber") Then
                    txtVoucher.Text = ""
                Else
                    txtVoucher.Text = dr("vouchernumber")
                End If
    
                ' GET DRIVER
                ' -------------------------------------------------------------
                If dr("driverid") = "0" Then
                    ' Self Drive
                    rblTrips.Items(1).Selected = True
    
                    pnlDriven.Visible = False
                    pnlSelfDriven.Visible = True
    
                Else
                    ' Driven
                    rblTrips.Items(0).Selected = True
    
                    pnlSelfDriven.Visible = False
                    pnlDriven.Visible = True
    
                    ddlDriver.ClearSelection()
                    ddlDriver.Items.FindByValue(dr("driverid")).Selected = True
                End If
    
                ' GET PASSENGER/S
                ' -------------------------------------------------------------
                If IsDBNull(dr("passengers")) Then
                    txtPassengers.Text = ""
                Else
                    txtPassengers.Text = dr("passengers")
                End If
                If IsDBNull(dr("passengercontact")) Then
                    txtPassengerContact.Text = ""
                Else
                    txtPassengerContact.Text = dr("passengercontact")
                End If
    
                ' GET COMMENTS
                ' -------------------------------------------------------------
                If IsDBNull(dr("comments")) Then
                    txtComments.Text = ""
                Else
                    txtComments.Text = dr("comments")
                End If
    
                ' GET VEHICLES
                ' -------------------------------------------------------------
                ddlVehicle.ClearSelection()
                ddlDriver.Items.FindByValue(dr("vehicleid")).Selected = True
    
                ' GET DATES AND TIMES
                ' -------------------------------------------------------------
                txtPickupDate.Text = Left(dr("res_date"), 10) ' USE DATE(trip.res_date) as res_date in the sql statement
    
                ucTimeIn.Time = dr("time_in")
    
                ucTimeOut.Time = dr("time_out")
    
            End If
            dr.Close()
        End Sub
    
        Protected Sub rblTrips_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblTrips.SelectedIndexChanged
    
            If rblTrips.SelectedItem.Value = "driven" Then
    
                pnlDriven.Visible = True
                pnlSelfDriven.Visible = False
    
            Else
    
                pnlSelfDriven.Visible = True
                pnlDriven.Visible = False
    
            End If
        End Sub
    
    End Class
    

    As stated, this code executes perfectly, so I'm really at a loss as to what the problem is here.

    I've tried Cleaning and Rebuilding the Solution, but it still hasn't fixed anything, so any insights are welcome!

  • Ortund
    Ortund over 11 years
    I don't want multi-select otherwise I'd have used something other than a DropDownList. Does it look like that's what I'm going for? Because if yes, then that's the problem...
  • Cᴏʀʏ
    Cᴏʀʏ over 11 years
    @Ortund: Sorry, I misinterpreted your question.