Access combobox properties inside array of comboboxes

陌路散爱 提交于 2019-12-13 04:47:06

问题


I have an array of combo boxes that are dynamically added to a windows form in VB.Net using Visual Studio 2010.

I would like to access the cboBox.list and cboBox.selecteditem properties, and I absolutely can if I use

                dim cboList() as ComboBox = {}

                ReDim Preserve cboList(cboList.Count)
                Dim location As New System.Drawing.Point(FieldX, FieldY)

                cboList(cboList.Count - 1) = New ComboBox
                With cboList(cboList.Count - 1)
                    .Name = "cboName"
                    .Location = location
                    .Size = Size
                    .TabIndex = 1
                End With

And then to access it I use either

     cboList(0).Items 

or

     cboList(0).SelectedIndex

Because these are generated from information in the database, where I store their name, X/Y location, etc., and may be added at different times while the program is running, I may not have the same combobox in 0 location each time. I've been trying to find a way to do this:

   cbolist("ComboName").Items

And have come up dry on the internet. Is there a way to use the combobox name in the array to find the find the proper combobox, and if so, how?

I'm using VB.Net Framework 3.5 in Visual Studio 10.


回答1:


Yes, you need to use a Dictionary(Of String, ComboBox) instead of an array:

Dim cboDictionary as Dictionary(Of String, ComboBox)
Dim cbo As New ComboBox
With cbo
  '...
End With
cboDictionary.Add(cbo.Name, cbo)

Notice by doing so you would also get increased performance, if you have many ComboBoxes, and their number is changing often. This is because Dictionary is optimized for this scenario, lookup, add and remove operations in most cases all run in O(1) time.

An array does not have lookup functionality, so it would require iteration to find an element, and a new array needs to be created to add or remove an element (which you are doing with ReDim). In contrast, Dictionary does not recreate itself every time.



来源:https://stackoverflow.com/questions/24518178/access-combobox-properties-inside-array-of-comboboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!