2011-03-11 60 views
1

我需要在运行时添加类型标签的arr。在运行时添加控件时无法处理事件

我正在制作一个程序,它将从不同标签的数据库中检索员工姓名。

点击每个员工的姓名(标签),它会在msgbox中显示关于该员工的所有信息。

我使用下面的代码来创建标签。由于标签的数量不固定,我使用了一个数组。

dim withevents lblArr() as Label 'declared in the class 

在子程序(表格负载):

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

子程序不是什么? – Blorgbeard 2011-03-11 14:34:13

+0

支持这种Handles子句我想。是的,使用AddHandler。 – 2011-03-11 15:51:52

回答

4

您需要使用AddHandler将事件处理程序链接到控件。

Look at this guide

+0

代码不会编译,因为子例程不处理任何控件数组事件。 (处理lblArr(0).click) – Pramod 2011-03-11 15:21:21

+1

摆脱'Handles xxx'并像我说的那样,使用'AddHandler'将事件处理程序链接到控件。 – mdm 2011-03-11 15:27:52

+0

+1正确的解决方案,但你没有解释*为什么* Pramod正在解决这个问题。我建议你说:“你需要使用'AddHandler'来动态地**将一个事件处理程序链接到一个数组中的控件** Handles不支持数组中的控件**” – MarkJ 2011-03-11 16:46:15

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)。子DynamicLabel_Click中的sender对象将包含对哪个标签进行了单击的引用。

相关问题