我有一个带有picturecontrol的表单(默认为black bg),下面有一个flowlayoutpanel。在表单的加载上,它循环浏览图像文件夹,并在flowlayoutpanel内创建缩略图(picturecontrol)。我想要做的是动态添加一个click事件,让用户使用其中一个缩略图更改主picturecontrol图像。
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_click子中没有声明“temp”。
有什么建议吗?
答案 0 :(得分: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
答案 1 :(得分:0)
我建议您使用:
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
这样可以避免运行时错误和空指针异常