VB.NET有很多值得学习的地方,这里我们主要介绍VB.NET ButtonArray类,包括介绍在VB.NET中使用控件数组等方面。

首先创建一个Button类型控件数组:
1、创建“Windows应用程序”类型的工程,添加名为VB.NET ButtonArray类,并使该类继承 System.Collection.CollectionBase 类。System.Collections.CollectionBase类是.NET框架类库中为集合操作提供抽象的基类,通过对它的继承可以为我们的VB.NET ButtonArray类具备集合增加、删除、索引的功能。
2、为VB.NET ButtonArray类添加ParentForm属性,即控件组所在窗体,创建初始化函数(构造函数);
3、为控件数组类增加AddItem方法,该方法在控件数组类中添加成员;
4、为控件数组类增加RemoveItem方法,该方法在控件数组中删除一个成员。
示例代码:
- Public Class ButtonArray
 - Inherits System.Collections.CollectionBase
 - Private ReadOnly ParentForm As System.Windows.Forms.Form
 - Public Sub New(ByVal pForm As System.Windows.Forms.Form)
 - ParentForm = pForm
 - End Sub
 - Default Public ReadOnly Property Item(ByVal index As Integer) As System.Windows.Forms.Button
 - Get
 - Return Me.List.Item(index) @# ButtonArray的List'属性从CollectionBase 继承
 - End Get
 - End Property
 - Public Sub AddItem()
 - Dim btnItem As New System.Windows.Forms.Button
 - Me.List.Add(btnItem)
 - ParentForm.Controls.Add(btnItem)'向窗体中增加控件
 - btnItem.Tag = Me.Count@#Count属性从CollectionBase 继承
 - btnItem.Top = Me.Count * 30
 - btnItem.Left = 200
 - btnItem.Text = "Button" & Me.Count.ToString
 - AddHandler btnItem.Click, AddressOf btnItem_Click '绑定事件处理程序
 - End Sub
 - Public Sub AddItem(ByVal btnItem As System.Windows.Forms.Button)
 - Me.List.Add(btnItem)
 - AddHandler btnItem.Click, AddressOf btnItem_Click '绑定事件处理程序
 - End Sub
 - Public Sub RemoveItem()
 - If Me.Count > 0 Then
 - ParentForm.Controls.Remove(Me(Me.Count - 1))
 - Me.List.RemoveAt(Me.Count - 1)
 - End If
 - End Sub
 - Public Sub btnItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 - MsgBox("点击:" & sender.GetType().ToString & CType(CType(sender, Button).Tag, String))
 - End Sub
 - End Class