如何在VB.NET中向动态创建的控件添加事件处理程序?

时间:2012-11-28 20:57:38

标签: vb.net visual-studio-2008 event-handling

我在这个论坛和其他网站上搜索并看过无数样本,但我仍然坚持这个问题; 我想为动态创建的PictureBox-es添加一个Click Handler并在其上传递一个参数,以便我知道哪个图片框被点击了。

这是我目前的代码:

Public Class frmMbarimAbonimi

Private Sub frmMbarimAbonimi_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'FitnessdbDataSet.clients' table. You can move, or remove it, as needed.
    'Me.ClientsTableAdapter.Fill(Me.FitnessdbDataSet.clients)

    '===============
    Dim dt As DataTable = PaPaguar()
    Dim i As Integer = 0

    Dim gr(dt.Rows.Count) As GroupBox
    Dim pp(dt.Rows.Count) As PictureBox
    Dim lb(dt.Rows.Count) As Label


    For Each row As DataRow In dt.Rows

        gr(i) = New GroupBox
        gr(i).Width = 200
        gr(i).Height = 180

        pp(i) = New PictureBox
        pp(i).SizeMode = PictureBoxSizeMode.StretchImage

        lb(i) = New Label



        '-------------------------
        Try
            Using str As Stream = File.OpenRead("C:\Fotot\" + dt.Rows(i).Item("Foto"))
                pp(i).Image = Image.FromStream(str)
            End Using

            lb(i).Text = dt.Rows(i).Item("Emer")

        Catch ex As Exception

            MsgBox("Fotoja nuk mund te ngarkohet, ju lutem realizoheni nje foto tjeter!!!")

        End Try
        '-------------------------
        pp(i).Visible = True
        pp(i).Width = 200
        pp(i).Height = 150

        AddHandler pp(i).Click, AddressOf testini



        gr(i).Controls.Add(pp(i))

        lb(i).Visible = True
        lb(i).Width = 200
        lb(i).Height = 30
        lb(i).Left = pp(i).Left
        lb(i).Top = pp(i).Top + 150
        lb(i).BackColor = Color.WhiteSmoke
        lb(i).BringToFront()
        gr(i).Controls.Add(lb(i))

        flpanel.Controls.Add(gr(i))

        i = i + 1
    Next row
End Sub 
End Class

所以我试图使用AddHandler pp(i)。点击,AddressOf testini但显然这不允许我用一个参数调用“testini”来识别点击了哪个图片框。

有人能指出我正确的方向还是给出一些建议?非常感谢。

1 个答案:

答案 0 :(得分:3)

您需要在创建的PictureBox中添加一些内容以在事件处理程序中标识它们,因为您无法更改添加“参数”的Click事件处理程序的签名

例如,您可以设置名称属性

pp(i) = New GroupBox
pp(i).Name = "PictureBox" + i.ToString

然后在事件处理程序中,您可以识别出您的图片框将发件人对象转换为图片框并抓取Name属性。
请记住,发件人始终是触发事件的控件。在你的情况下,总是你的dinamically创建PictureBoxes之一

Private Sub testini(sender As Object, e As System.EventArgs) 
     Dim pb As PictureBox = DirectCast(sender, PictureBox)
     Dim pbIdentity As String = pb.Name
     .....
End Sub