【问题标题】:How do I get a value from a dynamic control?如何从动态控件中获取值?
【发布时间】:2015-06-24 11:07:49
【问题描述】:

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

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 子中声明。

有什么建议吗?

【问题讨论】:

    标签: vb.net event-handling dynamic-controls


    【解决方案1】:

    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
    

    【讨论】:

    • 谢谢,正是我想要的:)
    【解决方案2】:

    我建议你使用:

    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
    

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

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 2021-12-20
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多