How to select a value from a DropDownList that has been returned from a database

advertisements

I have a web update form where every control is a property of the same table. It should work this way: Whenever I select a value from the main(the first) dropdownlist, a query should be run getting all of the fields(properties) and filling the other controls depending of the value I selected.

Event Code:

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DropDownList1.SelectedIndexChanged
        Dim objModel As New ModelDAO ' the data access class taht contains search method
        Dim myobject = objModel.searchObject(DropDownList1.Text)
        TextBox1.Text = myobject.Property2
        DropDownList2.SelectedValue = myobject.Property3 'what's wrong here?
    End Sub

Controls:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
                    DataSourceID="SqlDataSource1" DataTextField="MODEL" DataValueField="MODEL"
                    AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="-Select-" Value="" />
                    </asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
                        <asp:ListItem Value="0">-Select-</asp:ListItem>
                        <asp:ListItem>EDS</asp:ListItem>
                        <asp:ListItem>BDS</asp:ListItem>
                    </asp:DropDownList>

It works except the second DropDownList, I don't know how to change the selected value, I tried this:

DropDownList2.Text = myobject.Property3

and this:

DropDownList2.SelectedValue = myobject.Property3

But in both cases dropdownlist2 shows no selected item.

NOTE: Since textbox.text does get the right value I don't think search method has any problem, that's why I'm not posting it.


It doesn't work that way unfortunately. I'll give you pseudocode since I'm a C#er, but this is how I normally do it:

Dim int i = 0
ForEach Item in DDL.Items
    If Item.Text = databaseResult
        DDL.SelectedIndex = i
        ExitLoop
    EndIf
    i = i + 1
EndForEach

Here is the working code from the comment thread below:

Dim i As Integer = 0
For Each listitem In DropDownList1.Items
    If DropDownList3.SelectedItem.Text = myobject.property Then
        DropDownList3.SelectedIndex = i
        Exit For
    End If
    i = i + 1
Next