如何从动态控件中获取值?

How do I get a value from a dynamic control?

我有一个带有图片控件(默认为黑色 bg)的表单,下面有一个流布局面板。在表单加载时,它循环浏览图像文件夹并在流程布局面板内创建缩略图(图片控件)。我想做的是动态添加一个点击事件,让用户用其中一个缩略图更改主图片控件。

Private Sub TabImageLoad()
    Dim apppath As String = Application.StartupPath()
    Dim strFileSize As String = ""
    Dim di As New IO.DirectoryInfo(apppath + "\images")
    Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
    Dim fi As IO.FileInfo

    For Each fi In aryFi
        If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
            Dim temp As New PictureBox
            temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
            temp.Width = 100
            temp.Height = 75
            temp.Name = fi.ToString
            temp.Visible = True
            temp.SizeMode = PictureBoxSizeMode.StretchImage
            AddHandler temp.Click, AddressOf Me.temp_click
            FlowLayoutPanel1.Controls.Add(temp)
        End If
    Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    PictureBox1.Image = temp.Image
End Sub

这是我获取图像的子代码(注意 addhandler 尝试)和链接到 addhandler 的子代码。正如您可能已经猜到的那样,addhandler 不起作用,因为 "temp" 未在 temp_click 子中声明。

有什么建议吗?

sender 参数始终是触发事件的控件,在本例中是 PictureBox:

Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    PictureBox1.Image = pb.Image
End Sub

我建议你使用:

Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)

然后用

验证
if pbDynamic IsNot Nothing Then
    PictureBox1.Image = pbDynamic.image
end if

这样可以避免运行时错误和空指针异常