发布时间:2025-12-11 00:45:37 浏览次数:1
VB.NET的功能非常强大,可以实现代码的托管,以及强化代码架构,为程序员带来一个安全性较强的开发环境。我们在这里首先创建一个Button类型的VB.NET控件数组,来解释一下相关知识点。
1、创建“Windows应用程序”类型的工程,添加名为ButtonArray的类,并使该类继承 System.Collection.CollectionBase 类。System.Collections.CollectionBase类是.NET框架类库中为集合操作提供抽象的基类,通过对它的继承可以为我们的ButtonArray类具备集合增加、删除、索引的功能。
2、为ButtonArray类添加ParentForm属性,即控件组所在窗体,创建初始化函数(构造函数);
3、为控件数组类增加AddItem方法,该方法在控件数组类中添加成员;
4、为控件数组类增加RemoveItem方法,该方法在控件数组中删除一个成员。
VB.NET控件数组创建的示例代码:
PublicClassButtonArray
InheritsSystem.Collections.
CollectionBase
PrivateReadOnlyParentForm
AsSystem.Windows.Forms.Form
PublicSubNew(ByValpForm
AsSystem.Windows.Forms.Form)
ParentForm=pForm
EndSub
DefaultPublicReadOnlyPropertyItem
(ByValindexAsInteger)AsSystem.
Windows.Forms.ButtonGet
ReturnMe.List.Item(index)
'ButtonArray的List属性从
CollectionBase继承EndGet
EndProperty
PublicSubAddItem()
DimbtnItemAsNewSystem.
Windows.Forms.ButtonMe.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.ToStringAddHandlerbtnItem.Click,
AddressOfbtnItem_Click
'绑定事件处理程序EndSub
PublicSubAddItem(ByValbtnItem
AsSystem.Windows.Forms.Button)Me.List.Add(btnItem)
AddHandlerbtnItem.Click,
AddressOfbtnItem_Click
'绑定事件处理程序EndSub
PublicSubRemoveItem()
IfMe.Count>0Then
ParentForm.Controls.Remove
(Me(Me.Count-1))Me.List.RemoveAt(Me.Count-1)
EndIf
EndSub
PublicSubbtnItem_Click
(ByValsenderAsObject,
ByValeAsSystem.EventArgs)'在这里编写控件数组对点击事件的响应
'例如:
MsgBox("点击:"&sender.GetType().
ToString&CType(CType(sender,
Button).Tag,String))EndSub
EndClass