我需要在运行时添加类型标签的arr。
我正在制作一个程序,它将从不同标签的数据库中检索员工姓名。
点击每个员工姓名(标签)后,它将在msgbox中显示该员工的所有信息。
我使用以下代码创建标签。由于标签的数量不固定,我使用了一个数组。
dim withevents lblArr() as Label 'declared in the class
在子程序(Form load)中:
for i as integer=0 to NoofEmployee-1
redim lblArr(NoofEmployee-1)
lblArr(i)=new Label
' i assigned all the necessary property like size location etc..
me.controls.add(lblArr(i))
next
我宣布了另一个子程序:
private sub MyClick(sender as Object,e as EventArgs) **handles lblArr(0).click**
MsgBox("Hello")
end sub
代码没有编译,因为子程序不是
答案 0 :(得分:4)
您需要使用AddHandler
将事件处理程序链接到控件。
答案 1 :(得分:0)
首先,您需要定义一个充当事件处理程序的函数:
Private Sub DynamicLabel_Click(ByVal sender As Object, ByVal e As EventArgs)
' Do something, such as ...
Dim labelText as String = String.Empty
lableText = DirectCast(sender, Label).Text
MessageBox.Show(String.Format("The text of the Label is {0}", labelText)
End Sub
然后,当您动态创建Label控件时,需要告诉控件使用自定义事件处理函数:
Dim lbl As New Label
With lbl
' Set the properties of the Label here ...
' Now, tell the Label what function to use when clicked.
AddHandler .Click, AddressOf DynamicLabel_Click
End With
Panel1.Controls.Add(lbl)
请注意,我没有使用数组...不要认为VB6控制数组。他们并非真的有必要。相反,我将控件添加到容器(本例中为Panel1)。子sender
中的DynamicLabel_Click
对象将包含单击Label的引用。