Hi,
I would like to to to store the Name and Items of ComboBox into dictionary. With the below code,I am able to store them. However, Name of ComboBox is as counting ComboBox10 to ComboBox1n. I would like to store Name of ComboBox as ComboBox1,ComboBox2 rather than ComboBox10 to ComboBox1n for my futher propose.

It's not working with _dic.Add(ctl.Name, myCombo.Items(j).ToString) so I have to loop as _dic.Add(ctl.Name & j.ToString, myCombo.Items(j).ToString).

Would Appreciate your help and suggestion.

                 If TypeOf ctl Is ComboBox Then
                    myCombo = CType(ctl, ComboBox)
                    For j As Integer = 0 To myCombo.Items.Count - 1
                     _dic.Add(ctl.Name & j.ToString, myCombo.Items(j).ToString)
                 Next

Output
ComboBox10 One
ComboBox11 two
ComboBox12 Three

ComboBox20 Four
ComboBox21 Five
ComboBox22 Six

Recommended Answers

All 5 Replies

Try

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Dim dic As New Dictionary(Of String, String)

        For Each cbx As ComboBox In Me.Controls.OfType(Of ComboBox)()

            For i As Integer = 0 To cbx.Items.Count - 1
                dic.Add(cbx.Name & "-" & i, cbx.Items(i))
            Next

        Next

        'display the dictionary in a listbox for debug

        For Each key As String In dic.Keys
            ListBox1.Items.Add(key & ": " & dic(key))
        Next

    End Sub

End Class

This is also counting as
ComboBox1-0 One
ComboBox1-1 Two
ComboBox1-2 Three

I need Original name of ComboBox
e.g

ComboBox1 one
ComboBox1 Two
ComboBox1 Three

ComboBox2 Four
ComboBox2 Five
ComboBox2 Six

Hi
The dictionary does not allow duplicate key to be inserted in it.
However, I need to store the same name of the Combobox with it's Items for my future propose.
Is there a way to insert duplicate Keys into dinctionary?

You are correct. The dictionary does not allow duplicate keys, however, in my example there are no duplicate keys. I populated twp comboboxes with

the
quick
brown
fox

and the output is

ComboBox2-0: the
ComboBox2-1: quick
ComboBox2-2: brown
ComboBox2-3: fox
ComboBox1-0: the
ComboBox1-1: quick
ComboBox1-2: brown
ComboBox1-3: fox

You see that I avoided the duplicates by adding the index value to the key. Note the "-" separator so that you can recover the exact name of the combobox.

Thank you very much. I resolved my problem.

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.