【搬运】VB.NET控件数组示例2则

vb.net

代码
   
     
Public Class Form1

Dim But( 9 ) As Button ' 不要使用WithEvents和New进行声明

Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase .Load
' ##########################
' 此段代码放在窗体Load事件或构造函数(Sub New)中
For i As Integer = 0 To But.Length - 1 ' 循环枚举控件
But(i) = New Button ' 构建新实例
' ---------------------
' 开始定义控件属性
With But(i)
.Name
= " Button " & i
.Text
= .Name
.Tag
= i
.Location
= New Point( 0 , i * 22 )
End With
' ---------------------
AddHandler But(i).Click, AddressOf Button_Click ' 添加事件委托
Me .Controls.Add(But(i)) ' 将控件加入窗体
Next
' ##########################
End Sub

Private Sub Button_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
If Not TypeOf sender Is Button Then Return ' 如果sender对象不是按钮则退出过程
Dim b As Button = DirectCast (sender, Button) ' 强类型转换 等效方法有:CType、TryCast、DirectCast
Select Case b.Tag ' 你还可以使用如Name或Text等属性来区分按钮,使用Tag速度有些慢...
Case 0
Me .Text = " 0号按钮被单击 "
Case 1 To 5
MsgBox ( " 1-5号按钮被单击,即将移除本按钮的事件! " , 48 )
RemoveHandler b.Click, AddressOf Button_Click ' 移除事件委托
b.Text = " 没用的按钮 "
Case 7 , 9
MsgBox ( " 7,9 " , 64 )
Case 8
MsgBox ( " 恭祝大家鼠年发财! " )
End Select

' 这是另一种检测方式……
If sender.Equals(But( 6 )) Then
MsgBox ( " 你按下了按钮6对吧?! " )
End If
End Sub

End Class

 

 

代码
   
     
' 夜闻香原创,转载请保留此信息,万分感谢!
'
博客: http://hi.baidu.com/clso
'
论坛: http://clso.xuntan.com
'
QQ:315514678 E-mail:[email protected]
'
欢迎技术交流!

Public Class frmMain
Dim But As New List( Of Button) ' 创建一个按钮的泛型列表集合

Private Sub frmMain_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase .Load
For i As Integer = 0 To 9 ' 循环创建按钮
Dim b As New Button ' 实例化一个新按钮
With b ' 设置按钮属性
.Name = " Button " & i
.Text
= .Name
.Location
= New Point( 0 , i * 22 )
.Tag
= i
AddHandler .Click, AddressOf Buttons_Click ' 委托按钮的单击事件
Me .Controls.Add(b) ' 在窗体上添加按钮
But.Add(b) ' 将按钮添加到按钮集合中
End With
Next
End Sub

Private Sub Buttons_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim i As Integer = DirectCast (sender, Button).Tag ' 通过Tag来检测按钮
Select Case i
Case 1 To 5
MsgBox ( " 注意啦,接下来这个按钮就嗝儿P没用了! " , MsgBoxStyle.Exclamation)
RemoveHandler But.Item(i).Click, AddressOf Buttons_Click ' 移除事件委托
But.Item(i).Text = " 我挂了... "
Case 7 , 9
MsgBox ( " 不是7就是9! " )
Case 8
MsgBox ( " 你好坏~ (-_-b " )
Case Else
If sender.Equals(But( 6 )) Then ' 另一种检测方式
MsgBox ( " 我认得你,你是6号,对吧? " , MsgBoxStyle.Question)
Else
For Each b As Button In But ' 很方便的按钮Each循环枚举 ^_^
b.Text = " 帅呀... " ' 让所有的按钮都变化文本
Next
End If
End Select
End Sub

End Class

你可能感兴趣的:(VB.NET)