Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataBinding to drop down lists not working 1

Status
Not open for further replies.

Kalisto

Programmer
Feb 18, 2003
997
GB

Hi, Ive got a page with loads of controls on it that are data bound to an object behind the scenes.
In addition to that I have 2 DropDownLists which are bound to arrays.

I have set the selected value of one of the dropdown lists to a property from a class in my codebehind file, such that

Code:
<asp:dropdownlist id=ddlCurrent runat="server" Width="280px" DataValueField="ID" DataTextField="Name" DataSource="<%# arrCurrent %>" SelectedIndex="<%# _objInvestigation.Current %>">

Now

All the text boxes are bound in a similar way, and are displaying the values they pull from the class properties but
the dropDownList shows the top level entry.
Inspecting the data in debug shows that the ddl has the SelectedIndex is set to the correct value, but the control is not updating to show the selected value.

I am calling Page.DataBind after the array is intialised

So why are the text boxes displaying the correct information, but not the dropdown lists?
 
Rather than setting the DataSource in the ASPX portion of the page, you should set this on the Page Load event by using the DataSource and DataBind methods of the control. This will mean that code is seperate from the content and it will make it much easier to debug (as you can simply look at the objects and see what they contain).


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
Thansk Cas but that makes no difference. (Ive done that)
In the PageLoad Event, the control has the correct datasource, and is bound. I then set the SelectedIndex to an int pulled from my data class, but when the page renders it still draws it showing "Please Select" (Which is item 0.

(I have checked that my data source object isn't set to 0 as well)
 
Thansk Cas but that makes no difference. (Ive done that)
Can you post your page load event where you do this?


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 

Sure, this is one that isnt working.

Like I said, the irritating thing is that the textboxes are all binding to the text event on the page, to other properties in _objInvestigation and are working correctly.

the _obj propertyHostDistrict returns an integer that is within the range allowed for the values in the ddl.

But still it shows the 0th element. (and a breakpoint on where the selected index is set shows that the number has changed.

And putting the databind statement last makes no difference.
Code:
 If Not IsPostBack Then
 
 ddlHostDistrict.DataSource = arrListDistricts

 ddlHostDistrict.DataBind()

 ddlHostDistrict.SelectedIndex = _objInvestigation.HostDistrict
            End If

 
OK, instead of setting the SelectedIndex, try finding the relevant ListItem by using the FindByValue or FindByText methods and the setting it's selected property to True.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
Not made any difference. All my Drop Down lists contain the correct data, but they are all showing item 0 selected

Code:
  ddlHostDistrict.DataSource = arrListDistricts
  ddlHostDistrict.DataTextField = "DistrictName"
  ddlHostDistrict.DataValueField = "ID"

                '                ddlHostDistrict.SelectedIndex = _objInvestigation.HostDistrict
ddlHostDistrict.DataBind()
 ddlHostDistrict.Items.FindByText("Yeovil").Selected = True


'Trigger the Page Level Binding (Such as the controls)
                Page.DataBind()
 
Well, in the above example you posted, you bind the DropDownList, set the relevant Item to be selected and then rebind the DropDownList (by calling Page.DataBind) which will therefore reset the Item that is selected to the first entry in that list.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
I spotted that after posting, and removed it. Still works the same. My arraylist that Im binding to is an array of List Items.

Whats bugging me is Ive done this kind of thing before, it should not be difficult!
 
Post the entire code-behind file that you are using now then as I'm not sure what code you now have.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
You and Me both..

The entire cb file is large, so I'll post the section that creates the array and the Page_Load code

the array is a page level variable and is protected

Page_Load
Code:
If Not IsPostBack Then
   

ddlHostDistrict.DataSource = arrListDistricts
ddlHostDistrict.DataTextField = "DistrictName"
ddlHostDistrict.DataValueField = "ID"

ddlHostDistrict.DataBind()
ddlHostDistrict.Items.FindByText("Yeovil").Selected = True

End If

Array Population
Code:
 Private Sub BuildDropDowns()

        'Get the Arrays for the DropDown lists from the session
        arrListDistricts = Session("DistrictList")

        If arrListDistricts Is Nothing Then
            Dim reader As SqlClient.SqlDataReader
            arrListDistricts = New ArrayList

            Try
                'Create the 0 Record
                Dim districtTop As New District(0, "", "[Please Select]")
                arrListDistricts.Add(districtTop)

                'Read in the Data for the DropDownList
                reader = objData.ListLookup(DataHelper.LookupType.Districts)

                While reader.Read
                    Dim d = New District(reader.Item("ID"), reader.Item("DistrictCode"), reader.Item("DistrictName"))
                    arrListDistricts.Add(d)
                End While


                'Save into the Session to remove need for future DB access
                Session.Add("DistrictList", arrListDistricts)
            Catch ex As Exception
                objXMs.PublishException(New Exception("District List", ex))
                Throw ex

                Exit Try
                'Tidy Up Code
            Finally
                If Not reader Is Nothing Then
                    reader.Close()
                End If
            End Try
        End If
    End Sub
 
I still can't see where you are calling the BuildDropDowns function and there may be something else interfering with it. Post the whole code-behind file - we can pick out the bits that aren't important.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
ok, here it is..

For some brevity I have removed the Event Hanlers tied to the buttons, but they are event handlers, and are definitely not triggering on the page load / render cycle (Ive put break points in them all to be sure)

Code:
Public Class InvestigationDetailGeneral
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ddlProgressReviewDue As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlSelfInspectionReviewDue As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtMIRExtNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlMIRLocation As System.Web.UI.WebControls.DropDownList
    Protected WithEvents pnlManagement As System.Web.UI.WebControls.Panel
    Protected WithEvents txtDetailsOfIncident As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtIncidentLocation As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlHostDistrict As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtDateInvestigationCommenced As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtIncidentPrecis As System.Web.UI.WebControls.TextBox
    Protected WithEvents pnlIncident As System.Web.UI.WebControls.Panel
    Protected WithEvents btnIncidentDetails As System.Web.UI.WebControls.Button
    Protected WithEvents btnManagementDetails As System.Web.UI.WebControls.Button
    Protected WithEvents txtOperationName As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtRHURNNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtRHURNYear As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtRHURNCategory As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtRHURNForce As System.Web.UI.WebControls.TextBox
    Protected WithEvents vs1 As System.Web.UI.WebControls.ValidationSummary

    Protected WithEvents btnSave As System.Web.UI.WebControls.Button
    Protected WithEvents hlPickDateInvestigationCommenced As System.Web.UI.WebControls.HyperLink
    Protected WithEvents hlPickHeadOfCIDNotifiedDate As System.Web.UI.WebControls.HyperLink
    Protected WithEvents hlPickNominatedACCNotifiedDate As System.Web.UI.WebControls.HyperLink
    Protected WithEvents txtHeadOfCIDNotifiedDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtNominatedACCNotifiedDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents wucHeadOfCIDNotifiedTime As MCAS.wucTime
    Protected WithEvents wucNominatedACCNotifiedTime As MCAS.wucTime
    Protected WithEvents btnHeadOfCIDNotifiedNow As System.Web.UI.WebControls.Button
    Protected WithEvents btnNominatedACCNotifiedNow As System.Web.UI.WebControls.Button
    Protected WithEvents btnDateInvestigationCommencedToday As System.Web.UI.WebControls.Button
    Protected WithEvents hlNewMCIUOfficerName As System.Web.UI.WebControls.HyperLink
    Protected WithEvents txtMCIUOfficerNotifiedNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtHeadOfCIDNotifiedNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents HyperLink1 As System.Web.UI.WebControls.HyperLink
    Protected WithEvents HyperLink2 As System.Web.UI.WebControls.HyperLink
    Protected WithEvents lblDateInvestigationCommenced As System.Web.UI.WebControls.Label
    Protected WithEvents lblHeadOfCIDNotifiedName As System.Web.UI.WebControls.Label
    Protected WithEvents lblNominatedACCNotifiedName As System.Web.UI.WebControls.Label
    Protected WithEvents txtNominatedACCNotifiedNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents hlNewHeadOfCIDName As System.Web.UI.WebControls.HyperLink
    Protected WithEvents hlNewACCName As System.Web.UI.WebControls.HyperLink
    Protected WithEvents txtHeadOfCIDID As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtNominatedACCID As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnMCIUOfficerNotifiedEnter As System.Web.UI.WebControls.ImageButton
    Protected WithEvents btnHeadOfCIDNotifiedEnter As System.Web.UI.WebControls.ImageButton
    Protected WithEvents btnNominatedACCNotifiedEnter As System.Web.UI.WebControls.ImageButton
    Protected WithEvents hlNewMIRLocation As System.Web.UI.WebControls.HyperLink
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents wucInvestigationHeader As MCAS.wucInvestigationHeader

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object
    Protected arrListDistricts As New ArrayList   'TODO: Can be pushed into the cache and removed on page_Unload
    Protected arrMirLocations As New ArrayList
    Protected WithEvents WucDateTime_InvestigationStart As MCAS.wucDateTime
    Protected WithEvents lblMCIUOfficerNotifiedName As System.Web.UI.WebControls.Label
    Protected WithEvents txtMCIUOfficerID As System.Web.UI.WebControls.TextBox
    Protected WithEvents WucDateTimeMCIU As MCAS.wucDateTime


    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()

        'Retrieve info from the session about the current investigation
        Me._objInvestigation = Session("CurrentInvestigation")


        'Code that builds the arrays (if needed)
         BuildDropDowns()

    End Sub

#End Region

#Region " Page-level declarations "

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Possible values for the improvised tab control
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[7649]	22/05/2006	Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Enum eMode      'values for the page mode
        Incident = 0        'Showing incident details
        Management = 1      'Showing management details
    End Enum

    Protected _objInvestigation As MCAS.Investigation

    Dim objXMs As New ExceptionMethods
    Dim objData As New MCAS.DataHelper

#End Region

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Initialise the page
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[7649]	22/05/2006	Created
    '''     [70483] 22/11/2006  Moved the PopulateDDL method to within IsPostBack
    '''                         Removed Category DropDown List - This is already set and part of RHURn, so 
    '''                         should not be changed!
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Try


            Dim objWH As New WebHelper
            With objWH

      
                .DoStaffBuilderCallingScript(Me.txtMCIUOfficerID, Me.lblMCIUOfficerNotifiedName, _
                   Me.txtMCIUOfficerNotifiedNo, Me.hlNewMCIUOfficerName, , , 5)
                .DoStaffBuilderCallingScript(Me.txtHeadOfCIDID, Me.lblHeadOfCIDNotifiedName, _
                    Me.txtHeadOfCIDNotifiedNo, Me.hlNewHeadOfCIDName, , , 6)
                .DoStaffBuilderCallingScript(Me.txtNominatedACCID, Me.lblNominatedACCNotifiedName, _
                    Me.txtNominatedACCNotifiedNo, Me.hlNewACCName, , , 7)

                'And some javascript to work the MIR Location popup
                .DoNewItemCallingScript(Me.ddlMIRLocation, Me.hlNewMIRLocation, , , 8)

            End With

            If Not IsPostBack Then


                wucInvestigationHeader.URN = _objInvestigation.RHURN
                wucInvestigationHeader.OperationName = _objInvestigation.OperationName
                'Show incident information first
                SwitchTabs(eMode.Incident)

                ddlHostDistrict.DataSource = arrListDistricts
                ddlHostDistrict.DataTextField = "DistrictName"
                ddlHostDistrict.DataValueField = "ID"

                ddlHostDistrict.DataBind()
                ddlHostDistrict.Items.FindByText("Yeovil").Selected = True


            End If

            'Initialise the Date/Time User Controls
            WucDateTime_InvestigationStart.theDate = _objInvestigation.DateInvestigationCommenced
            WucDateTime_InvestigationStart.DateEnabled = True

            WucDateTimeMCIU.theDate = _objInvestigation.MCIUOfficerNotifiedDateAndTime
            WucDateTimeMCIU.DateEnabled = True
            WucDateTimeMCIU.TimeEnabled = True
            WucDateTimeMCIU.ShowTime = True



        Catch ex As Exception
            objXMs.PublishException(ex)
            Throw ex
        End Try

    End Sub

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Setup all the Arrays needed for drop down lists
    ''' 
    ''' these arrays will be stored in the session for future use
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[7649]	20/06/2006	Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Sub BuildDropDowns()

        'Get the Arrays for the DropDown lists from the session
        arrListDistricts = Session("DistrictList")
        arrMirLocations = Session("MIRLocationsList")

        If arrListDistricts Is Nothing Then
            Dim reader As SqlClient.SqlDataReader
            arrListDistricts = New ArrayList

            Try
                'Create the 0 Record
                Dim districtTop As New District(0, "", "[Please Select]")
                arrListDistricts.Add(districtTop)

                'Read in the Data for the DropDownList
                reader = objData.ListLookup(DataHelper.LookupType.Districts)

                While reader.Read
                    Dim d = New District(reader.Item("ID"), reader.Item("DistrictCode"), reader.Item("DistrictName"))
                    arrListDistricts.Add(d)
                End While


                'Save into the Session to remove need for future DB access
                Session.Add("DistrictList", arrListDistricts)
            Catch ex As Exception
                objXMs.PublishException(New Exception("District List", ex))
                Throw ex

                Exit Try
                'Tidy Up Code
            Finally
                If Not reader Is Nothing Then
                    reader.Close()
                End If
            End Try
        End If

        If arrMirLocations Is Nothing Then
            Dim reader As SqlClient.SqlDataReader
            arrMirLocations = New ArrayList

            Try
                'Create the 0 Record
                Dim mirTop As New MIRLocation("[Please Select]")
                arrMirLocations.Add(mirTop)

                'Read in the Data for the DropDownList
                reader = objData.ListLookup(DataHelper.LookupType.MIRLocations)
                While reader.Read
                    Dim d = New MIRLocation(CShort(reader.Item("ID")))
                    arrMirLocations.Add(d)
                End While


                'Save into teh Session to remove need for future DB access
                Session.Add("MIRLocationsList", arrMirLocations)

            Catch ex As Exception
                objXMs.PublishException(New Exception("MIR Locations List", ex))
                Throw ex

                Exit Try

            'Tidy Up Code
        Finally
                If Not reader Is Nothing Then
                    reader.Close()
                End If
            End Try
        End If

    End Sub


  
    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Switch to a specified tab
    ''' </summary>
    ''' <param name="Mode"></param>
    ''' <returns></returns>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[7649]	22/05/2006	Created
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Private Function SwitchTabs(ByVal Mode As eMode) As Boolean

        Try
            Dim objWH As New WebHelper

            'Hide all tabs except the one whose mode has been selected
            Me.pnlIncident.Visible = (Mode = eMode.Incident)
            Me.pnlManagement.Visible = (Mode = eMode.Management)

            'Deselect all buttons except the one that's been pressed
            With objWH
                .SelectButton(Me.btnIncidentDetails, (Mode = eMode.Incident))
                .SelectButton(Me.btnManagementDetails, (Mode = eMode.Management))
            End With
        Catch ex As Exception
            objXMs.PublishException(ex)
            Throw ex
        End Try
    End Function


   


End Class
 
Hmmm...I can't see anything from the above code that should stop the Item from being selected. What happens if you put a breakpoint at the end of the Page Load event and enter "? ddlCurrentCostCentres.SelectedValue" into the command window?


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
4" which was the index I was setting it to.

Im glad that its not me going mad if you can't see what might be causing it either!
 
Well, For anyone that reads this in the future, I know what is causing the issue, but Im not sure yet why or how!

The cause of my problem is a UserControl.As soon as I remove it from the page, it all works. The User Control does it's own DataBinding, so Im guessing that thats interfering with the main page databinding.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top