Search code examples
drop-down-menucopyruntimeitems

Different DropDownLists created at runtime do not allow selecting different items?


I need to create many dropdownlists at runtime and select a different item for each one. To avoid accessing the DB continuously I create a single dropdownlist of which I copy the items in the cloned dropdownlists. Strangely all the dropdownlists created select the item of the last dropdownlist and I don't understand why! I had to insert the cleaning of the selected items ["DlistClone.ClearSelection ()"] because otherwise the code goes wrong. Can anyone help me? thanks

   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim MyRow As New TableRow
    Dim MyCell As New TableCell

    Dim DList As DropDownList
    Dim DlistClone As DropDownList
    DList = New DropDownList
    DList.Items.Add("1")
    DList.Items.Add("2")
    DList.Items.Add("3")

    MyRow = New TableRow
    MyCell = New TableCell
    DlistClone = New DropDownList
    ClonaDList(DList, DlistClone)
    DlistClone.ClearSelection()
    DlistClone.Items.FindByText("3").Selected = True
    MyCell.Controls.Add(DlistClone)
    MyRow.Cells.Add(MyCell)

    Table1.Rows.Add(MyRow)

    MyRow = New TableRow
    MyCell = New TableCell
    DlistClone = New DropDownList
    ClonaDList(DList, DlistClone)
    DlistClone.ClearSelection()
    DlistClone.Items.FindByText("2").Selected = True
    MyCell.Controls.Add(DlistClone)
    MyRow.Cells.Add(MyCell)

    Table1.Rows.Add(MyRow)
End Sub

Sub ClonaDList(ByVal Origine As DropDownList, ByVal Destinazione As DropDownList)
    Dim I As Integer
    Dim EleList As ListItem

    For I = 0 To Origine.Items.Count - 1
        EleList = Origine.Items(I)
        Destinazione.Items.Add(EleList)
    Next I
End Sub

Solution

  • Ok, I got it myself! When I do

    EleList = Origin.Items (I)
    Destination.Items.Add (EleList)

    I create an inadvertent binding between the source Dropdownlist and the destination one. To interrupt the binding I must necessarily use a bridge between the two controls, in this case I use the Listitem object by setting the 2 properties in 2 successive steps

    Sub ClonaDList(ByRef Origine As DropDownList, ByRef Destinazione As DropDownList)
        Dim I As Integer
        Dim EleList As ListItem
    
        For I = 0 To Origine.Items.Count - 1
            EleList = New ListItem
            EleList.Text = Origine.Items(I).Text
            EleList.Value = Origine.Items(I).Value
            Destinazione.Items.Add(EleList)
        Next I
    End Sub
    

    Did I say it right?