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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ComboBox ObjectCollection is empty

Status
Not open for further replies.

SBendBuckeye

Programmer
May 22, 2002
2,166
US
Hello all,

I am using the following code to try and match an item in a combobox. The ObjectCollection count is zero when it should be 3 as the combobox Items.Count = 3.
Code:
' Fill combobox with integers.
Me.ComboBox1.Items.Add(1)
Me.ComboBox1.Items.Add(2)
Me.ComboBox1.Items.Add(3)
Me.ComboBox1.SelectedIndex = 1
Code:
Public Sub SetSelectedItem(ByVal selectedItem As Object)
    Try
        If Not Me.ComboBox1.FindForm.ContainsFocus Then Return
        ' Get combobox items collection.
        Dim collection As ObjectCollection = _
            New ObjectCollection(Me.ComboBox1)
        ' Get associated index for requested item.
        Me.ComboBox1.SelectedIndex = _
            collection.IndexOf(selectedItem)
    Catch ex As Exception
        Throw
    End Try
End Sub 'SetSelectedItem
Thanks in advance for any ideas and/or suggestions!


 
Why not just set the Text property of the ComboBox to the value required?

For example:

Code:
Public Sub SetSelectedItem(ByVal selectedItem As Integer)
    Try
        If Not Me.ComboBox1.FindForm.ContainsFocus Then Return
        Me.ComboBox1.Text = selectedItem.ToString
    Catch ex As Exception
        Throw
    End Try
End Sub 'SetSelectedItem

This should do what you want.

Also did you mean to select the value 2 when initialising the ComboBox which is what Me.ComboBox.SelectedIndex = 1 will do? The Items are indexed from zero.

Bob Boffin
 
Hello Bob,

Thanks for the response. The example I posted was a simplified version. The code is actually in an inherited control and I needed to be able to get the index for a requested item.

The following works correctly for the inherited class (from ComboBox), which is why I use Me in the code below:
Code:
Public Sub SetSelectedItem(ByVal selectedItem As Object)
    Me.SelectedIndex = _
        DirectCast(Me.Items, ComboBox.ObjectCollection).IndexOf(selectedItem)
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top