Solved

ASP.NET error "Cannot have multiple items selected in a DropDownList"

Posted on 2014-09-17
23
2,750 Views
Last Modified: 2014-10-01
This is the error I am getting but only on the odd item?


Cannot have multiple items selected in a DropDownList.
  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) +9630133
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
   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) +128
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.WebControls.TableCell.RenderContents(HtmlTextWriter writer) +31
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
   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) +128
   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) +57
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer) +211
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
   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) +128
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +102
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
   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) +128
   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) +57
   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) +1386
 
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212 

Open in new window

The page shows a Listview in the left side of the page with a select column and a data pager to scroll through the list of site visits (the application is used to record data about security officers in stores they are protecting and the supervisors who use this application can check if the officer is doing certain aspects of his/her job properly and whether their appearance and uniform is acceptable). When the user locates a record they want to view or amend they can click the select item in the list and this then updates the main right side of the page which has multiple drop down lists and text boxes which are populated from the SiteVisit table.  The Listview has an "OnSelectedIndexChanged" parameter in the declaration i.e.:
<asp:ListView ID="lstSiteVisits" ViewStateMode="Enabled" runat="server" DataKeyNames="SiteVisitID" OnSelectedIndexChanging="lstSiteVisits_SelectedIndexChanging" OnSelectedIndexChanged="lstSiteVisits_SelectedIndexChanged" EnableViewState="true" EnablePersistedSelection="true">

Whilst trying to unravel what was causing this error I also tried using OnSelectedIndexChanging="lstSiteVisits_SelectedIndexChanging" at the moment there is a code behind for this but it has nothing in it so that entry could be removed.

In the "lstSiteVisits_SelectedIndexChanged" code I have this:

   
Protected Sub lstSiteVisits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstSiteVisits.SelectedIndexChanged
        Dim SelID As Integer = 0
        SelID = lstSiteVisits.SelectedDataKey.Value
        PopulateScreen(SelID)
        
    End Sub

Open in new window


PopulateScreen looks like this:

   
Public Function PopulateScreen(SiteVisitID As Integer) As Boolean
        Dim s As New SiteVisit
        Dim ItemToSelect As ListItem = Nothing

        Try

            If s.GetRecord(SiteVisitID) Then
                lblSiteVisitID.Text = "Site Visit ID: " & Format(s.SiteVisitID, "00000000")
                lblActionID.Text = "Action ID: " & Format(s.fkActionCalendarID, "00000000")

                cboLocation.ClearSelection()
                ItemToSelect = cboLocation.Items.FindByText(s.Location)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboLocation.SelectedIndex = -1
                End If

                mskDate.Text = DF(s.SVDate)

                cboTypeOfVisit.ClearSelection()
                ItemToSelect = cboTypeOfVisit.Items.FindByText(s.TypeOfVisit)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboTypeOfVisit.SelectedIndex = -1
                End If

                mskTime.Text = TF(s.SVTime, 1)

                cboOfficerName.ClearSelection()
                ItemToSelect = cboOfficerName.Items.FindByText(s.OfficerName)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboOfficerName.SelectedIndex = -1
                End If

                txtSIALicenceNumber.Text = s.SIALicenceNumber
                txtSIALicenceExpiry.Text = DF(s.SIALicenceExpiry)
                txtIDBadgeExpiry.Text = DF(s.IDBadgeExpiry)

                cboPocketBookCompletion.ClearSelection()
                ItemToSelect = cboPocketBookCompletion.Items.FindByText(s.PocketBookCompletion)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboPocketBookCompletion.SelectedIndex = -1
                End If

                cboRecordOfIncidentsComplete.ClearSelection()
                ItemToSelect = cboRecordOfIncidentsComplete.Items.FindByText(s.RecordOfIncidentsCompletion)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboRecordOfIncidentsComplete.SelectedIndex = -1
                End If

                cboECRCrimeReportEtc.ClearSelection()
                ItemToSelect = cboECRCrimeReportEtc.Items.FindByText(s.ECRCrimeReportingFaxed)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboECRCrimeReportEtc.SelectedIndex = -1
                End If

                cboDailyOccurBookComplete.ClearSelection()
                ItemToSelect = cboDailyOccurBookComplete.Items.FindByText(s.DailyOccurenceBook)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboDailyOccurBookComplete.SelectedIndex = -1
                End If

                ItemToSelect = cbTop20LinesIdent.Items.FindByText(s.Top20LineChecked)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cbTop20LinesIdent.SelectedIndex = -1
                End If

                cboAssignInstructionsUnderstood.ClearSelection()
                If s.AssignmentInstructionsUnderstoodAndSignedYN Then
                    ItemToSelect = cboAssignInstructionsUnderstood.Items.FindByText("Yes")
                Else
                    ItemToSelect = cboAssignInstructionsUnderstood.Items.FindByText("No")
                End If
                ItemToSelect.Selected = True

                txtAssignInstructionsInPlaceDate.Text = DF(s.AssignmentInstructionsInPlaceDate)

                cboAssignInstructionsInPlaceYN.ClearSelection()
                If s.AssignmentInstructionInPlaceYN Then
                    ItemToSelect = cboAssignInstructionsInPlaceYN.Items.FindByText("Yes")
                Else
                    ItemToSelect = cboAssignInstructionsInPlaceYN.Items.FindByText("No")
                End If
                ItemToSelect.Selected = True

                txtHealthAndSafetyInPlaceDate.Text = DF(s.HealthAndSafetyDate)

                cboHealthAndSafetyInPlaceYN.ClearSelection()
                If s.HealthAndSafetyYN Then
                    ItemToSelect = cboHealthAndSafetyInPlaceYN.Items.FindByText("Yes")
                Else
                    ItemToSelect = cboHealthAndSafetyInPlaceYN.Items.FindByText("No")
                End If
                ItemToSelect.Selected = True

                cboHealthAndSafetyUnderstoodAndSigned.ClearSelection()
                If s.HealthAndSafetyRiskAssUnderstoodAndSignedYN Then
                    ItemToSelect = cboHealthAndSafetyUnderstoodAndSigned.Items.FindByText("Yes")
                Else
                    ItemToSelect = cboHealthAndSafetyUnderstoodAndSigned.Items.FindByText("No")
                End If
                ItemToSelect.Selected = True

                cboJumper.ClearSelection()
                ItemToSelect = cboJumper.Items.FindByText(s.JumperDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboJumper.SelectedIndex = -1
                End If

                cboJacket.ClearSelection()
                ItemToSelect = cboJacket.Items.FindByText(s.JacketDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboJacket.SelectedIndex = -1
                End If

                cboShirt.ClearSelection()
                ItemToSelect = cboShirt.Items.FindByText(s.ShirtDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboShirt.SelectedIndex = -1
                End If

                cboTrousers.ClearSelection()
                ItemToSelect = cboTrousers.Items.FindByText(s.TrousersDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboTrousers.SelectedIndex = -1
                End If

                cboTie.ClearSelection()
                ItemToSelect = cboTie.Items.FindByText(s.TieDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboTie.SelectedIndex = -1
                End If

                cboEppaulettes.ClearSelection()
                ItemToSelect = cboEppaulettes.Items.FindByText(s.EppaulettesDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboEppaulettes.SelectedIndex = -1
                End If

                cboHiVisJacket.ClearSelection()
                ItemToSelect = cboHiVisJacket.Items.FindByText(s.HiVisJacketDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboHiVisJacket.SelectedIndex = -1
                End If

                cboShoesBoots.ClearSelection()
                ItemToSelect = cboShoesBoots.Items.FindByText(s.ShoesBootsDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboShoesBoots.SelectedIndex = -1
                End If

                txtSecurityOfficerSign.Text = s.SecurityOfficerSign

                cboManagerName.ClearSelection()
                ItemToSelect = cboManagerName.Items.FindByText(s.ManagerDropbox)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboManagerName.SelectedIndex = -1
                End If

                txtTrainingGiven.Text = s.TrainingInstructionGivenDetailsbox
                txtTrainingGivenDate.Text = DF(s.TrainingInstructionGivenDate)
                txtFollowUpReq.Text = s.FollowUpActionReqDetails
                txtFollowUpReqDate.Text = DF(s.FollowUpActionReqDate)
            Else
                lblSiteVisitID.Text = "Site Visit ID: " & Format(0, "00000000")
                lblActionID.Text = "Action ID: " & Format(0, "00000000")
            End If

            Return True

        Catch ex As Exception

            ErrorMessage = PEH("PopulateScreen", "frmSiteVisitForm", ex.Message)
            Response.Redirect("ErrorPage.aspx")

            Return False

        Finally


            If Not IsNothing(s) Then
                s.Dispose()
            End If

        End Try

    End Function

Open in new window

This just populates all of the drop lists and text boxes in the main part of the page when the user clicks a selection in the list.

The whole thing is working fine for nearly all the items in the list but if I page to the last page of records and select the first item at the top of the list I get the above crash.

Stepping through the code when I click the selected item, the call to "lstSiteVisits_SelectedIndexChanged" is made, the ID of the record I want to view is obtained from the SelectedDataKey.Value and the call to PopulateScreen is made, this runs through without any error, as soon as the first call is complete lstSiteVisits_SelectedIndexChanged is called again a second time (not sure why this occurs but would be interested to know why?) and again the PopulateScreen processes without any error.  After that a call to the Page_PreRender occurs:

   
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
        If Not Page.IsPostBack Then
            PopulateSiteVisitsList(-1, "", "")
        End If
    End Sub

Open in new window


Because this is a PostBack call the PopulateSiteVisitList call is not made.  Then the code moves to my "DataPagerSiteVisits_PreRender" code:

   
Protected Sub DataPagerSiteVisits_PreRender(sender As Object, e As EventArgs)


        If optLocation.Checked Then
            PopulateSiteVisitsList(-1, "Location", txtSearch.Text)
        End If
        If optOfficerName.Checked Then
            PopulateSiteVisitsList(-1, "OfficerName", txtSearch.Text)
        End If
        If optTypeOfVisit.Checked Then
            PopulateSiteVisitsList(-1, "TypeOfVisit", txtSearch.Text)
        End If

    End Sub

Open in new window

This runs the PopulateSiteVisitsList call using the parameters for whichever option button I have selected (the user can filter the ListView by entering a search term into the "txtSearch" text box and clicking a search button), when I am populating the page I can either use the entered text and search type or if the search box is left empty it returns all records the option button is defaulted to the "Location" search type which means the records are ordered by site if no text is entered in the search box.

So in the instance where there is no search text entered the "PopulateSiteVisitsList" is called with the parameters as follows:
PopulateSiteVisitsList(-1, "Location", "") as there is no search text.

This is PopulateSiteVisitsList:

    Public Sub PopulateSiteVisitsList(SiteVisitIDToSelect As Integer, SearchType As String, SearchText As String)
        Dim n As Integer = 0
        Dim ss As New SiteVisitColl
        Dim s As New SiteVisit
        Dim SelItem As Integer = 0
        Try
            lstSiteVisits.Items.Clear()
            lstSiteVisits.DataSource = Nothing

            'Get the collection of site visit records
            ss = s.GetAllSiteVisits(SearchType, SearchText)

            If IsNothing(ss) Then
                Exit Sub
            End If

            If ss.Count > 0 Then

                If SiteVisitIDToSelect >= 0 Then 'if -1 then we do not attempt to identify the selected item.

                    If SiteVisitIDToSelect > 0 Then
                        For n = 0 To ss.Count - 1
                            If ss(n).SiteVisitID = SiteVisitIDToSelect Then
                                SelItem = n
                                Exit For
                            End If
                        Next
                    Else
                        lstSiteVisits.SelectedIndex = 0
                    End If

                    lstSiteVisits.DataSource = ss
                    lstSiteVisits.DataBind()
                    lstSiteVisits.SelectedIndex = SelItem
                Else
                    lstSiteVisits.DataSource = ss
                    lstSiteVisits.DataBind()
                End If

            End If



        Catch ex As Exception

            ErrorMessage = PEH("PopulateSiteVisitsList", "frmSiteVisitForm", ex.Message)
            Response.Redirect("ErrorPage.aspx")

        Finally

            If Not IsNothing(ss) Then
                ss.Dispose()
                s.Dispose()
            End If

        End Try
    End Sub

Open in new window

When this routine completes (again there is no error as the code is being stepped through) there is a short delay and then the error occurs, so it feels like the error is being thrown outside of my code?

Can anyone point me to why this error is occurring and how to fix it.  I have researched this error on the net and nothing I have found seems to make any difference?

Siv
0
Comment
Question by:Siv
  • 13
  • 7
  • 2
23 Comments
 
LVL 12

Expert Comment

by:Ramkisan Jagtap
Comment Utility
Where are you getting this error? I mean which line of code?
0
 

Author Comment

by:Siv
Comment Utility
Ramkisan,

As I mentioned above this error occurs after my code completes so it appears to be outside my code? When I step the code I do not get the error at all it's occurring after I step out of the following sub:

Protected Sub DataPagerSiteVisits_PreRender(sender As Object, e As EventArgs)


         If optLocation.Checked Then
             PopulateSiteVisitsList(-1, "Location", txtSearch.Text)
         End If
         If optOfficerName.Checked Then
             PopulateSiteVisitsList(-1, "OfficerName", txtSearch.Text)
         End If
         If optTypeOfVisit.Checked Then
             PopulateSiteVisitsList(-1, "TypeOfVisit", txtSearch.Text)
         End If

     End Sub

I stepped the code all the way through the call to "PopulateSiteVisitsList" and it returns from that without throwing any error and then I hit the "Exit Sub" above and clearly something happens just after that and then I get the error page displayed in IE.

So as far as I can tell it's occurring after my code completes and just as the page is drawn in IE.

Siv
0
 

Author Comment

by:Siv
Comment Utility
As you can see from the stack trace it doesn't mention any particular dropdown name in the stack trace so I cannot work out where the issue is?

Siv
0
 
LVL 12

Expert Comment

by:Ramkisan Jagtap
Comment Utility
Please debug and check where it is giving this error?
0
 

Author Comment

by:Siv
Comment Utility
I don't know how to do any more than I have, what do you mean by debug (I put a break point on the first line of the "lstSiteVisits_SelectedIndexChanged" subroutine and then step the code line by line from that point onwards) and in doing so I find that no error is thrown until I get to the end of the "DataPagerSiteVisits_PreRender" sub which is the last call before the page is output to Internet Explorer.  The code from my perspective is complete, I don't particularly want it to call the " DataPagerSiteVisits_PreRender" but that seems to be as a result of rendering the page which calls the "Page_PreRender" and then the "DataPagerSiteVisits_PreRender" as part of normal page creation.

Once the "DataPagerSiteVisits_PreRender"  is called it calls a routine which draws the ListView again (PopulateSiteVisitsList) and I have stepped that process and again it does not generate any errors, it's only when that completes and I return to the "DataPagerSiteVisits_PreRender" routine and step to the "Exit Sub" at the end of that at which point, the page is drawn to IE I assume that the IE page shows the error.  All the stuff that I do that selects the relevant items in the dropdown lists is stepped through without any error.  My only concern is why that gets called twice, it may be that my code is called the first time by the action of selecting the item in the ListView which populates the screen and then that gets called again by a postback? In my early attempts to suss out what was going on I actually put a check for "IsPostback" and if it was I then skipped the PopulateScreen call but that seemed to stop the selection process working in the ListView and the selection highlighter was always one refresh behind.

Siv
0
 

Author Comment

by:Siv
Comment Utility
I have now put a Try Catch around the DataPagerSiteVisits_PreRender routine as this is the routine that when I exit it leads to the error report and after doing this and restarting the code I still get the stack trace so clearly the error occurs after my code? This is how the routine looks now with my error handler wrapped around it and my error routine is not called so the error is after my code and somewhere in ASP.NET or the Visual Basic part of Dot Net?

    Protected Sub DataPagerSiteVisits_PreRender(sender As Object, e As EventArgs)
        Try

            If optLocation.Checked Then
                PopulateSiteVisitsList(-1, "Location", txtSearch.Text)
            End If
            If optOfficerName.Checked Then
                PopulateSiteVisitsList(-1, "OfficerName", txtSearch.Text)
            End If
            If optTypeOfVisit.Checked Then
                PopulateSiteVisitsList(-1, "TypeOfVisit", txtSearch.Text)
            End If

        Catch ex As Exception

            ErrorMessage = PEH("DataPagerSiteVisits_PreRender", "frmSiteVisit", ex.Message)
            Response.Redirect("ErrorPage.aspx")

        End Try
0
 
LVL 41

Accepted Solution

by:
pcelba earned 500 total points
Comment Utility
The exception did not occur during Prerender but in Render event which is fired automatically after Prerender...

If some of the Render methods sets the selected item in the list but another one is selected already and the list does not allow multiselections then the exception must appear...

So the solution is: Allow multiselections then you may see more selected items in the list or set the List.SelectedIndex to -1 or find all places where the SelectedIndex changes in your code (and remember the fact it can be set automatically in the background).

You may place the breakpoint just before the line which causes the exception (visible in the stack trace) and check all the values and the listbox state. It will tell more.
0
 

Author Comment

by:Siv
Comment Utility
pcelba,

Can you point me to where the problem line is as I cannot see anything in the stack trace that appears to be a droplist in my code?

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
Look at the first four lines of stack trace:
   System.Web.UI.WebControls.DropDownList.VerifyMultiSelect() +106
   System.Web.UI.WebControls.ListControl.RenderContents(HtmlTextWriter writer) +9630133
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32

The ListControl.RenderContents seems to be generated (or nonsense which could explain the exception) but you should place breakpoints to these methods. VerifyMultiSelect() seems to be your code so check it as the first instance.

How many items contains your ListControl?
0
 

Author Comment

by:Siv
Comment Utility
pcelba,

That's not my function, I think this is .Net code it's hitting the problem in. In my code I explicitly clear every drop list before I try to set it to the value that is held in the database, if the value is matched I set the SelectedIndex to the item that matches, if not it stays cleared, here is the first droplist I try and select an item in, it is copied from the "PopulateScreen" function I have listed in my original question:

               Dim ItemToSelect As ListItem = Nothing

                cboLocation.ClearSelection()
                ItemToSelect = cboLocation.Items.FindByText(s.Location)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cboLocation.SelectedIndex = -1
                End If

s is a class that matches to the "SiteVisit" table in my SQL database and holds the record we are currently displaying in the screen. I have checked my code and as far as I can tell every occasion where I am trying to make a selection in a drop list I first run the "ClearSelection" on the relevant drop down that I am trying to select an item in.

So if for any reason the item in the database is not found the drop down list's selection has been cleared first so I should never hit a situation where I have more than one selected item?

I think the issue could be something to do with the fact that the page is being redrawn twice.  The reason I say this is that I have a save button on the page and I have a click event that is called to save the record on screen and if I step the code in that it gets called OK and just when I think it has completed the click event fires again and it's generating a second row of the same data in the database.  I think if I could pin down why everything on this page seems to get called twice, this issue might go away?

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
So if some method is called twice then place a breakpoint to this method and check the calling stack. It should identify the method call origin. A quick workaround is to identify such duplicate call and return immediately which can help temporarily.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Siv
Comment Utility
Here it is:

Call Stack
As you can see it's not very helpful?

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
0
 

Author Comment

by:Siv
Comment Utility
Pavel,
OK this is the stack trace with external code turned on when entering the SelectedIndexChanging event the first time (ie when the entry in the ListView is first clicked:

>      App_Web_ihso54ew.dll!frmSiteVisit.lstSiteVisits_SelectedIndexChanging(Object sender, System.Web.UI.WebControls.ListViewSelectEventArgs e) Line 85      Basic
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.OnSelectedIndexChanging(System.Web.UI.WebControls.ListViewSelectEventArgs e)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.HandleSelect(int itemIndex)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.HandleEvent(System.EventArgs e, bool causesValidation, string validationGroup)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.OnBubbleEvent(object source, System.EventArgs e)      Unknown
       System.Web.dll!System.Web.UI.Control.RaiseBubbleEvent(object source, System.EventArgs args)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListViewDataItem.OnBubbleEvent(object source, System.EventArgs e)      Unknown
       System.Web.dll!System.Web.UI.Control.RaiseBubbleEvent(object source, System.EventArgs args)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.OnCommand(System.Web.UI.WebControls.CommandEventArgs e)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl, string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Collections.Specialized.NameValueCollection postData)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest()      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext context)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest(System.Web.HttpContext context)      Unknown
       App_Web_ihso54ew.dll!ASP.frmsitevisit_aspx.ProcessRequest(System.Web.HttpContext context)      Basic
       System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()      Unknown
       System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously)      Unknown
       System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)      Unknown
       System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb)      Unknown
       System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)      Unknown
       System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)      Unknown
       System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)      Unknown
       [AppDomain Transition]      

This is the stack trace the second time it is called and just prior to the crash occuring:

>      App_Web_ihso54ew.dll!frmSiteVisit.lstSiteVisits_SelectedIndexChanging(Object sender, System.Web.UI.WebControls.ListViewSelectEventArgs e) Line 85      Basic
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.OnSelectedIndexChanging(System.Web.UI.WebControls.ListViewSelectEventArgs e)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.HandleSelect(int itemIndex)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.HandleEvent(System.EventArgs e, bool causesValidation, string validationGroup)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListView.OnBubbleEvent(object source, System.EventArgs e)      Unknown
       System.Web.dll!System.Web.UI.Control.RaiseBubbleEvent(object source, System.EventArgs args)      Unknown
       System.Web.Extensions.dll!System.Web.UI.WebControls.ListViewDataItem.OnBubbleEvent(object source, System.EventArgs e)      Unknown
       System.Web.dll!System.Web.UI.Control.RaiseBubbleEvent(object source, System.EventArgs args)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.OnCommand(System.Web.UI.WebControls.CommandEventArgs e)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl, string eventArgument)      Unknown
       System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Collections.Specialized.NameValueCollection postData)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest()      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext context)      Unknown
       System.Web.dll!System.Web.UI.Page.ProcessRequest(System.Web.HttpContext context)      Unknown
       App_Web_ihso54ew.dll!ASP.frmsitevisit_aspx.ProcessRequest(System.Web.HttpContext context)      Basic
       System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()      Unknown
       System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously)      Unknown
       System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)      Unknown
       System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb)      Unknown
       System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)      Unknown
       System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)      Unknown
       System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)      Unknown
       [AppDomain Transition]      

I am confused?

Siv
0
 

Author Comment

by:Siv
Comment Utility
I just stepped the code again after changing the PopulateScreen routine to see if I made a change to the routines made any difference, the change I made was to remove the SelectedIndex=-1.

I.e. From:

                 cboLocation.ClearSelection()
                 ItemToSelect = cboLocation.Items.FindByText(s.Location)
                 If Not IsNothing(ItemToSelect) Then
                     ItemToSelect.Selected = True
                 Else
                     cboLocation.SelectedIndex = -1
                 End If

To:

                 cboLocation.ClearSelection()
                 ItemToSelect = cboLocation.Items.FindByText(s.Location)
                 If Not IsNothing(ItemToSelect) Then
                     ItemToSelect.Selected = True
                 End If

As I was concerned that somehow the setting of the SelectedIndex might be the issue?

It seems to not make any difference, what I did notice was that the calls being made to the "lstSiteVisits_SelectedIndexChanged" routine were sometimes hitting an error where the "lstSiteVisits.SelectedDataKey" was set to NOTHING so I trapped that by changing the routine like this:

    Protected Sub lstSiteVisits_SelectedIndexChanging(sender As Object, e As ListViewSelectEventArgs) Handles lstSiteVisits.SelectedIndexChanging
        Dim SelID As Integer = 0
        Try

            If Not IsNothing(lstSiteVisits.SelectedDataKey) Then
                SelID = lstSiteVisits.SelectedDataKey.Value
                PopulateScreen(SelID)
            End If

        Catch ex As Exception

            ErrorMessage = PEH("lstSiteVisits_SelectedIndexChanging", "frmSiteVisit", ex.Message)
            Response.Redirect("ErrorPage.aspx")

        End Try
    End Sub

Again this did not stop the error occurring?

I would really like to know why everything on this page gets called twice, it seems to be postbacks?  Could I send you the full aspx page and the code behind page, perhaps you can see something so obvious that I am missing?

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
Setting SelectedIndex = -1 cannot cause the "Cannot have multiple items selected in a DropDownList." exception.

You should rather check if there is some item selected prior to the
SelID = lstSiteVisits.SelectedDataKey.Value
PopulateScreen(SelID)

and if yes then unselect it first or don't call the PopulateScreen which causes the exception probably.

You code would be very long reading to me probably. I am also learning ASP.NET but on different heap of code...

You have to code each web page event as an independent entity so it can be called from zero to several times without side effects. Each step you do in the code must check if it is possible to do it. And default values must be ready in the case the event is not fired...
0
 

Author Comment

by:Siv
Comment Utility
Pavel,

This is my problem as it appears that the error occurs when not in my code so it's very hard to see where the issue is.

The more I look into it the more I am of the opinion that I need to understand why the page keeps making events fire multiple times. The thing that seems to happen last before the error occurs is the call to DataPagerSiteVisits_PreRender which I find strange as at this point I am not changing the page of ListView data I am just selecting one of the items in the ListView that's controlled by the DataPager.

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
I've found these two pages helpful to understand the ASP.NET events:
http://devio.wordpress.com/2008/03/26/aspnet-page-and-control-lifecycle/
http://blogs.thesitedoctor.co.uk/tim/2006/06/30/Complete+Lifecycle+Of+An+ASPNet+Page+And+Controls.aspx

It is something which needs long learning and which also needs to study code from others...

Both PreRender and Render events are fired and you have to live with it :-(.
0
 

Author Comment

by:Siv
Comment Utility
Pavel,

Thanks for these I'll have a look at them and see if I can figure out what's causing the problem.

Siv
0
 

Author Comment

by:Siv
Comment Utility
Pavel,
Finally after going round the houses and back again I have poured over my code that populates the screen and found the bug, it was there in plain view all the time.  The following is taken from my code for as it was originally in the "PopulateScreen" question right at the top:

                End If

                ItemToSelect = cbTop20LinesIdent.Items.FindByText(s.Top20LineChecked)
                If Not IsNothing(ItemToSelect) Then
                    ItemToSelect.Selected = True
                Else
                    cbTop20LinesIdent.SelectedIndex = -1
                End If

                cboAssignInstructionsUnderstood.ClearSelection()

Open in new window


The issue is that I had forgotten the ClearSelection method on the "cbTop20LinesIdent" DropDown list. The net result was that if when visiting one record that DropDown was populated and then you went to another item that was also populated, because I had not cleared the DropDown first, it was being assigned another selected value and of course triggered the error. It's just annoying that the error does not get raised when in my code but only when my code has finished processing and Visual Studio sends the rendered page to IE. It's only then that the error is hit and the stack trace you get gives no clue as to which drop down it is that is being given two selected items.

Because I was convinced that it was something to do with the double posting effect I wasted a lot of time hunting for a fix for that rather than focussing on what the error was telling me.  Ah well, you live and learn.

So this issue is now cleared and my page works beautifully.

Thanks for all your help, even though you didn't give me the actual solution your help talking it through with me has allowed me to find the issue. I was getting nowhere on my own.

Siv
0
 

Author Closing Comment

by:Siv
Comment Utility
Pavel,

This was the solution in that it is true what you are saying I just couldn't see that it was me failing to clear one of the twenty or so drop downs that appear on my page in the PopulateScreen function. If anyone else is having this issue see my last comment where I highlight the lines causing the issue.

Thanks for talking this through with me it helped having someone else to bounce my thoughts off.

Siv
0
 
LVL 41

Expert Comment

by:pcelba
Comment Utility
You are welcome!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video discusses moving either the default database or any database to a new volume.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now