Hi
I am storing name and texts of controls (Label, Button, ComboBox, ListBox, etc.) into a dictionary.
With ContainsKey, I am able to find the texts of Labels, Buttons, and RadioButtons. However, I am getting problem to find the items of ComboBox. Appreciate if you have an idea.

 If _dic.ContainsKey(selectedControl.Name) Then
  Debug.Print("I found the text """ & _dic(selectedControl.Name) & """")

Dani AI

Generated

Nice follow-up to — the key point is that a ComboBox’s choices live in an Items collection (and when data-bound they can be DataRowView or custom objects), so the Text/Caption approach that works for Label/Button won’t give you the whole list. Use a safe lookup (handles nested containers), read each item with GetItemText (so DisplayMember is respected), and handle non-string items explicitly.

A concise, robust pattern:

' find the control anywhere on the form
Dim matches() As Control = Me.Controls.Find(selectedControl.Name, True)
Dim cb As ComboBox = Nothing
If matches.Length > 0 Then
    cb = TryCast(matches(0), ComboBox)
End If

If cb IsNot Nothing Then
    For Each itm As Object In cb.Items
        Dim displayText As String = cb.GetItemText(itm)
        ' process or store displayText
    Next
End If

If the ComboBox is data-bound, prefer saving the underlying value (SelectedValue or the value column) rather than the display text, so you can restore the same semantic choice later. To save all items into a dictionary without losing type information, store a List(Of String) of display texts (or a List(Of Object) for values):

Dim itemsList = cb.Items.Cast(Of Object).Select(Function(i) cb.GetItemText(i)).ToList()
_myComboItemsDict(selectedControl.Name) = itemsList

When restoring, clear the Items, AddRange (or loop Add), and set SelectedIndex/SelectedValue afterwards. Extra tips: use BeginUpdate/EndUpdate while repopulating for performance; use TryCast to avoid exceptions; access controls only from the UI thread (Invoke if needed). These small details cover the common pitfalls that stop enumerate-and-store approaches from working reliably.

Recommended Answers

All 2 Replies

Try:

Dim TempComboBox As CombBox = DirectCast(Me.Controls(selectedControl.Name), ComboBox)
For Each item As String In TempComboBox.Items
    'Do Stuff
Next

On a side not, the same concept can be used for the 'Text' property without the need for a dictionary.

Thank you tinstaafl. It worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.