在visual basic中创建控件数组

时间:2013-08-02 18:29:48

标签: vb.net visual-studio-2013

好的,这是相关的代码:

Public Shared compSelect(9) As ComboBox
Public Shared compPercent(9) As TextBox
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Data.LoadComponents("C:/Users/Jon/Documents/Visual Studio 2013/Projects/QuickBlend/QuickBlend/QuickBlend/Resources/databaseText.txt")
    MsgBox("finished loading")
    MainForm.compSelect = {CompSelect1, CompSelect2, CompSelect3, CompSelect4, CompSelect5, CompSelect6, CompSelect7, CompSelect8, CompSelect9, CompSelect10}
    MainForm.compPercent = {CompPercent1, CompPercent2, CompPercent3, CompPercent4, CompPercent5, CompPercent6, CompPercent7, CompPercent8, CompPercent9, CompPercent10}
    For Each box As ComboBox In MainForm.compSelect
        box.DataSource = Data.Components
        box.DisplayMember = "Name"
        For Each comp As String In Data.ComponentNames
            box.Items.Add(comp)
        Next
        MsgBox("looped")
    Next
    MsgBox("finished loop")
End Sub

正如您所看到的,我已经放置了各种MsgBoxes以查看到底发生了什么。它从不显示“循环”消息框。任何人都可以向我解释为什么它完全跳过for循环?一直在研究这个并且厌倦了它。在此先感谢您的帮助! =)

2 个答案:

答案 0 :(得分:2)

MainForm.compSelect应该是Me.compSelect,因为这是实例(已经填充了组合框),而不仅仅是尚未填充的对象的完全限定名称。

答案 1 :(得分:0)

您的问题是您正在为comboBox设置数据源,然后尝试向其添加项目。 .NET不喜欢这样,只会在没有警告的情况下退出尝试执行此操作的Sub(除非您添加了异常处理)。你的代码应该是......

Public Shared compSelect(9) As ComboBox
Public Shared compPercent(9) As TextBox
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Data.LoadComponents("C:/Users/Jon/Documents/Visual Studio 2013/Projects/QuickBlend/QuickBlend/QuickBlend/Resources/databaseText.txt")
MsgBox("finished loading")
MainForm.compSelect = {CompSelect1, CompSelect2, CompSelect3, CompSelect4, CompSelect5, CompSelect6, CompSelect7, CompSelect8, CompSelect9, CompSelect10}
MainForm.compPercent = {CompPercent1, CompPercent2, CompPercent3, CompPercent4, CompPercent5, CompPercent6, CompPercent7, CompPercent8, CompPercent9, CompPercent10}
For Each box As ComboBox In MainForm.compSelect
    box.DataSource = Data.Components
    box.DisplayMember = "Name"
    'take this stuff out, it is not needed
    'For Each comp As String In Data.ComponentNames
        'box.Items.Add(comp)
    'Next
    MsgBox("looped")
Next
MsgBox("finished loop")
End Sub