将事件添加到动态创建的按钮

时间:2015-01-15 06:17:42

标签: vb.net

我的表格上有4个图片框。每当选择新图片时,将填充下一个可用框,并在该图片框中创建一个按钮。我希望该按钮能够删除该特定图片框中的图像。我知道如何创建一个事件处理程序,然后将地址添加到按钮,我不知道该怎么做是如何编写代码,以实际删除分配的框上指定的图像。这是我加载图片和创建按钮的代码:

    Private Sub btnAddImage_Click(sender As Object, e As EventArgs) Handles btnAddImage.Click, btnUploadImage.Click 4

        Dim btn As Button = New Button
        btn.Text = "Remove Image"


        'Procedure places the pictures in each empty picturebox in sequence
        ofdBrowsePictures.Multiselect = False
        ofdBrowsePictures.Title = "Select Image to Upload"
        ofdBrowsePictures.Filter = "Image Files |*.jpg*"

        If ofdBrowsePictures.ShowDialog() = Windows.Forms.DialogResult.OK Then

            'create array of each picture box and check if they are empty
            'Check if the picturebox contains a tag with the image path
            Dim PBs() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
            Dim nextPB = PBs.Where(Function(x) IsNothing(x.Image)).FirstOrDefault

            If Not IsNothing(nextPB) Then

                'if the box does not contain a image path, then place the picture on that box
                nextPB.ImageLocation = ofdBrowsePictures.FileName
                nextPB.Tag = nextPB.ImageLocation.ToString

                'add a button
                nextPB.Controls.Add(btn)

                'Create a border style on the image
                nextPB.BorderStyle = BorderStyle.FixedSingle

            End If
        End If
End Sub

2 个答案:

答案 0 :(得分:1)

what I do not know how to do is how to write the code so as to actually delete the assigned image on the assigned box

我认为“删除图像”表示从图片框中删除,而不是从磁盘中删除。

' what is 4???
Private Sub btnAddImage_Click(sender As Object, 
      e As EventArgs) Handles btnAddImage.Click, btnUploadImage.Click 4

    Dim btn As Button = New Button
    btn.Text = "Remove Image"

    ' bla bla bla set the imagelocation

    AddHandler btn.Click, AddressOf RemoveImage_Click
    pb1.Controls.Add(btn)          ' btn.parent = this pb
End Sub

Private Sub RemoveImage_Click(sender As Object, e As EventArgs) Handles Button9.Click
    Dim btn As Button = CType(sender, Button)

    ' clear image
    CType(btn.Parent, PictureBox).ImageLocation = ""

    RemoveHandler btn.Click, AddressOf RemoveImage_Click

    ' remove the control 
    pb1.Controls.Remove(btn)

    ' if you remove a control, dispose of it
    btn.Dispose()
End Sub

我不确定在检查下一个PB之前是否会调用对话框(我也不会创建新的Button),因为如果没有{{1>你似乎想要什么都不做使用。

有关处理删除控件的详细信息,请参阅:

基本上,表单会在您关闭它们时处理控件。如果删除一个控件,表单不再有引用,也不能。因此,您应该处理它们。

答案 1 :(得分:0)

其中任何一个都清除了使用ImageLocation设置的图片框图像:

PictureBox1.Image = Nothing
PictureBox1.ImageLocation = ""
PictureBox1.ImageLocation = String.Empty