第16节 关于控件数组

  控件数组是某控件产生的下标的相同对象名称的对象集合。

  如名称为:command1(0) command1(1) command1(2)就是一个控件数组。

  对一个控件的复制或在同一个工程中添加同名控件,既可生成控件数组。这些控件都有相同的名字,但它们的索引号Index属性值自动从0开始按生成控件的顺序排出控件数组元素下标。利用这个特点可以使用循环来控制控件数组做相同的操作,使程序大大简化。

例:个人分数统计

Private Sub Command1_Click()

  For i = 0 To 7

    s = s + Val(Text1(i).Text)

  Next i

  Label10.Caption = s

  Label12.Caption = s / 8

End Sub

Private Sub Command2_Click()

  For i = 0 To 7

    Text1(i).Text = 100

  Next i

End Sub

Private Sub Command3_Click()

  End

End Sub

 

 

例:四则运算练习

Rem 没有用控件数组的程序

Private Sub Form_Load()

   OptDiv.Value = True

End Sub

Private Sub OptAdd_Click()

   lblOpertor.Caption = OptAdd.Caption

End Sub

Private Sub OptSub_Click()

   lblOpertor.Caption = OptSub.Caption

End Sub

Private Sub OptMul_Click()

   lblOpertor.Caption = OptMul.Caption

End Sub

Private Sub OptDiv_Click()

   lblOpertor.Caption = OptDiv.Caption

End Sub

Private Sub ComOk_Click()

   If lblOpertor.Caption = "+" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) + Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "-" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) - Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "*" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) * Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "/" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) / Val(TxtOpertor2.Text)

   End If

End Sub

 

Rem 用数组控件的程序

Private Sub Form_Load()

   Option1(3).Value = True

End Sub

Private Sub Option1_Click(Index As Integer)

    lblOpertor.Caption = Option1(Index).Caption

End Sub

Private Sub ComOk_Click()

   If lblOpertor.Caption = "+" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) + Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "-" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) - Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "*" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) * Val(TxtOpertor2.Text)

   End If

   If lblOpertor.Caption = "/" Then

      TxtOpertor.Text = Val(TxtOpertor1.Text) / Val(TxtOpertor2.Text)

   End If

End Sub