我有几个名为Array1,Array2,Array3,...的数组,还有一些名为的组合框:cboArray1,cboArray2,cboArray3,....
如何编写GENERAL代码以将每个数组的元素添加到相应的combox中。我知道下面的代码是有效的,但它不是GENERAL和ABSTRACT。
For i = 0 To Array1.Length - 1
cboArray1.Items.Add(Array1(i))
Next
For i = 0 To Array2.Length - 1
cboArray2.Items.Add(Array2(i))
Next
...
工作程序可能如下:1。找到表格中的所有组合框(简单)2。提取combox的名称(简单)3。从代码中找到类似命名的数组(困难)4 .... .... > 我可以使用像List这样的其他集合......如果有意义的话。
答案 0 :(得分:0)
以下是您要求使用反思的内容......虽然我不确定这是多么有用:
Public Class Form1
Private Array1 As String() = {"cat", "dog", "fish"}
Private Array2 As String() = {"alpha", "beta", "gamma"}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WireComboBoxes(Me)
End Sub
Private Sub WireComboBoxes(ByVal container As Control)
For Each ctl As Control In container.Controls
If TypeOf ctl Is ComboBox AndAlso ctl.Name.ToUpper.StartsWith("CBO") Then
Dim cb As ComboBox = DirectCast(ctl, ComboBox)
Dim arrName As String = cb.Name.Substring(3)
Dim fi As System.Reflection.FieldInfo = Me.GetType.GetField(arrName, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
If Not IsNothing(fi) Then
cb.DataSource = fi.GetValue(Me)
End If
ElseIf ctl.HasChildren Then
WireComboBoxes(ctl)
End If
Next
End Sub
End Class