有没有办法循环我建立的TextBoxes并定义每个.Text?

时间:2016-07-20 17:34:12

标签: .net vb.net winforms

我在TextBoxes中有一组8 WinForm,并且我已经创建了一个对象数组,供它们包含。在Form的初始化中,我想将每个TextBox.text设置为Environ("USERPROFILE") & "\Documents"以显示每个框的默认文件路径。这些框用于根据用户输入显示要加载的文件。

目前代码如下:

Public Sub New()
    InitializeComponent()

    BWGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
    BWBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
    ChGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
    ChBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
    CCGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
    CCBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
    PPGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
    PPBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
End Sub

有没有办法让它在For循环中运行(类似于下面,除了这不起作用)来定义每个盒子?这样我也可以统一修改每个框,例如[Excel.Application].[Excel.Workbook].Open(TextBoxesList(x).Text)

Public Sub New()
    InitializeComponent()
    Dim TextBoxesList As Object = {BWGPTextBox, BWBRTextBox, _
                                      ChBRTextBox, ChGPTextBox, _
                                      CCGPTextBox, CCBRTextBox, _
                                      PPGPTextBox, PPBRTextBox}
    For Each x In TextBoxesList
        TextBoxesList(x).GetType() ' = Environ("USERPROFILE") & "\Documents"
    Next
End Sub

1 个答案:

答案 0 :(得分:2)

存储特定类型As Object通常是一个错误,因为它隐藏了存储的实际类型:

Dim TextBoxesList As Object = {BWGPTextBox, BWBRTextBox, 
                                  ChBRTextBox, ChGPTextBox, 
                                  CCGPTextBox, CCBRTextBox, 
                                  PPGPTextBox, PPBRTextBox}

生成的数组存储了阻止您访问TextBox特定属性的对象。从类型化数组开始:

' DECLARE the array at the form level:
Private TextBoxesList As TextBox()
....
' initialize it AFTER the constructor runs:
TextBoxesList = {BWGPTextBox, BWBRTextBox, 
                                  ChBRTextBox, ChGPTextBox, 
                                  CCGPTextBox, CCBRTextBox, 
                                  PPGPTextBox, PPBRTextBox}

' then loop:
For Each tb As TextBox in TextBoxesList 
    tb.Text = "foo"          
Next 

存储和迭代As TextBox允许轻松访问TextBox属性。您也可以按索引循环:

For n As Int32 = 0 to TextBoxesList.Count-1
    TextBoxesList(n).Text = "foo"          
Next