0

我在 Visual Basic 2010 的设计视图中有一个很大的对象列表,我需要为其更改一堆属性,所以我当然尝试使用数组而不是使用 50-60 行来完成重复性任务。但似乎有一个引用该对象的问题,它似乎只是从中获取信息。我知道这是一个糟糕的解释,但也许你看到它就会明白。

    Dim objectsToClear As Array = _
    {lblDailyRoundTrip, lblDaysWorked, lblFillBoxes, lblMilesPerGallon, lblMonthlyInsurance, _
     lblMonthlyMaintenance, lblMonthlyParking, tbDailyRoundTrip, tbDaysWorked, tbMilesPerGallon, _
     tbMonthlyInsurance, tbMonthlyMaintenance, tbMonthlyParking}

        For i = LBound(objectsToClear) To UBound(objectsToClear)
        objectsToClear(i).Text = ""
        objectsToClear(i).Visible = False
    Next
4

2 回答 2

1

试试这个:

Dim objectsToClear As Array = { lblDailyRoundTrip, 
                                lblDaysWorked, 
                                lblFillBoxes, 
                                lblMilesPerGallon, 
                                lblMonthlyInsurance, 
                                lblMonthlyMaintenance, 
                                lblMonthlyParking, 
                                tbDailyRoundTrip, 
                                tbDaysWorked, 
                                tbMilesPerGallon, 
                                tbMonthlyInsurance, 
                                tbMonthlyMaintenance, 
                                tbMonthlyParking }

For Each item In objectsToClear
    item.Text = String.Empty
    item.Visible = False
Next item

PS - 你真的应该有Option Strict On,你应该强输入你的数组。

于 2013-10-16T02:44:26.827 回答
1

由于您似乎只对更改.Text.Visible属性感兴趣,因此您可以按名称找到控件,如下所示:

Dim returnValue As Control()
returnValue = Me.Controls.Find(objectsToClear(i), True)

注意:True参数是关于是否搜索所有孩子,这听起来像是你想做的。阅读Control.ControlCollection.Find 方法文档以获取更多信息。

既然您有一个与您指定的名称匹配的控件集合,请遍历该集合中的控件并设置属性值,如下所示:

For Each c As Control In returnValue
    c.Text = ""
    c.Visible = False
Next
于 2013-10-16T02:45:52.830 回答