动态添加事件到图片框vb.net

时间:2016-12-30 15:56:45

标签: vb.net dynamic

我试图在vb.net中动态添加图片框。

如果我玩变种,改变" i"值我可以将图像和事件添加到最后创建的图片框中(我只能点击最后的图片)。

但是当我使用下面的代码时,它会说出边界之外的东西(索引超出矩阵的边界)。

我做错了什么? TKS

Imports System.IO

Public Class FormMain
Dim Path1 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\1.png"
Dim Path2 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\2.png" 

Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CreateImages()
End Sub

Dim i As Integer
Dim Logo(i) As PictureBox

Sub CreateImages()
    Dim i As Integer = TextBoxNumberImages.Text

    For i = 0 To i - 1
        Logo(i) = New PictureBox
        Logo(i).Name = "Image" + Str(i)
        Panel1.Controls.Add(Logo(i))
        Logo(i).Image = Image.FromFile(Path1)
        Logo(i).SizeMode = PictureBoxSizeMode.StretchImage

        AddHandler Logo(i).Click, AddressOf _Click

    Next
End Sub

'------ADD EVENT----

Dim IsImageSelected(i) As Boolean 

Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)

    If IsImageSelected(i) = False Then
        Logo(i).Image = Image.FromFile(Path2)
        IsImageSelected(i) = True
    Else
        Logo(i).Image = Image.FromFile(Path1)
        IsImageSelected(i) = False
    End If
End Sub

---- ---- EDIT

我刚将var声明更改为函数内部:

Sub CreateImages()
    Dim i As Integer = TextBoxNumberImages.Text
    Dim Logo(i) As PictureBox

    For i = 0 To i - 1
        Logo(i) = New PictureBox
        Logo(i).Name = "Image" + Str(i)
        Panel1.Controls.Add(Logo(i))
        Logo(i).Image = Image.FromFile(Path1)
        Logo(i).SizeMode = PictureBoxSizeMode.StretchImage

        AddHandler Logo(i).Click, AddressOf _Click

    Next
End Sub

现在它以我想要的方式创建图像,但我无法访问事件中的图片框。帮助

1 个答案:

答案 0 :(得分:0)

不要使用数组,而是使用List(Of PictureBox)。您还可以将所选状态存储在PictureBox的Tag()中。要获取对单击的PictureBox的引用,请转换Sender参数。总之,它看起来像这样:

Private Logo As New List(Of PictureBox)

Sub CreateImages()
    Dim i As Integer = TextBoxNumberImages.Text

    For i = 0 To i - 1
        Dim pb As New PictureBox
        pb = New PictureBox
        pb.Tag = False ' <-- initial not selected state
        pb.Name = "Image" + Str(i)
        Panel1.Controls.Add(pb)
        pb.Image = Image.FromFile(Path1)
        pb.SizeMode = PictureBoxSizeMode.StretchImage
        AddHandler pb.Click, AddressOf _Click
        Logo.Add(pb)
    Next
End Sub

Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    Dim selected As Boolean = DirectCast(pb.Tag, Boolean)
    If selected = False Then
        pb.Image = Image.FromFile(Path2)
    Else
        pb.Image = Image.FromFile(Path1)
    End If
    pb.Tag = Not selected ' toggle selected state
End Sub