我如何将点击事件添加到从后面的代码中添加的图像按钮

时间:2019-05-03 19:03:42

标签: asp.net vb.net

我正在通过图像按钮从后面的代码加载页面上的文件夹中的所有图像。

图像已正确添加,但我想将onclick事件连接到动态添加的图像按钮。

下面是我的代码

  Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        For Each strfilename As String In Directory.GetFiles(Server.MapPath("~/glypics/"))
            Dim imgbtn As New ImageButton
            Dim fileinfo As New FileInfo(strfilename)


            imgbtn.ImageUrl = "~/glypics/" + fileinfo.Name
            imgbtn.Width = Unit.Pixel(250)
            Panel1.Controls.Add(imgbtn)
            imgbtn.Style.Add("padding", "3px")
  Next

    End Sub

2 个答案:

答案 0 :(得分:0)

在函数中添加Addhandler imgbtn.MouseClick, AddressOf imgbtn_MouseClick,然后创建被调用函数。

Sub imgbtn_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
    'Image Button clicked...
End Sub

答案 1 :(得分:0)

我不确定图像按钮是什么?但是假设它就像一个按钮,您只需要添加一个处理程序即可,可以通过多种方式完成该操作。

    Dim imgbtn As New Button
    AddHandler imgbtn.Click, Sub()
                                 'do stuff
                             End Sub

    Dim imgbtn As New Button
    AddHandler imgbtn.Click, AddressOf DoClick


Private Sub DoClick(sender As Object, e As EventArgs)
    'Do Stuff
End Sub

如果需要,后者更容易删除

RemoveHandler imgbtn.Click, AddressOf DoClick