使用相同的点击事件将图片加载到多个图片框中

Load images into multiple picture boxes using the same click event

我有一个包含 4 个图片框的面板的表单:

我有一个加载图像按钮,使用以下代码将图像加载到图片框中:

        'Procedure to upload images through the button click

    'open Dialog box to load image

    ofd.FileName = Nothing

    'Show dialog box above all froms

    ofd.Multiselect = False
    ofd.Title = "Select Image to Upload"
    ofd.Filter = "Image Files |*.jpg*"
    ofd.ShowDialog()

    'Select file and place on picture box
    If Not ofd.FileName = Nothing Then
        picBox.ImageLocation = ofd.FileName

    End If

    'Show the button to delete image
    btn.Visible = True

当我只填充一个框时,该过程运行良好,但现在我有 4 个框,我不想为每个框创建一个按钮。我的问题是,如何使用相同的过程(或类似的过程)将图片加载到第一个框以外的框中。

它们需要按顺序加载。例如,单击按钮,加载左上框,再次单击并加载右上框。因此,如果所有 4 个框都没有图像,则左上角在前,如果左上角有图像,则右上角在下一个,依此类推。

试试

dim i as integer
dim file as string
file = OpenFileDialog1.FileNames
 For Each file In OpenFileDialog1.FileNames
   if i=0
picturebox1. ImageLocation=file
elseif i=1
   picturebox2. ImageLocation=file
elseif i=2
   picturebox3. ImageLocation=file
elseif i=3
   picturebox4. ImageLocation=file
     end if
i+=1   
Next

按照你想要的顺序给出图片框的顺序。

您可以执行以下操作;只需替换名为 "PBs":

的数组中 PictureBoxes 的名称
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ofd.Multiselect = False
    ofd.Title = "Select Image to Upload"
    ofd.Filter = "Image Files |*.jpg*"
    If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
        Dim PBs() As PictureBox = {PictureBox1, PictureBox2, PictureBox3, PictureBox4}
        Dim nextPB = PBs.Where(Function(x) IsNothing(x.Image)).FirstOrDefault
        If Not IsNothing(nextPB) Then
            nextPB.ImageLocation = ofd.FileName
        End If
    End If
End Sub

另一个解决方案:

将 OpenFileDialog 的多选 属性 设置为 True,然后在 OpenFileDialog1_FileOK 事件中执行此操作:

For x = 0 To OpenFileDialog1.FileNames.Length - 1
    Dim Path As String = OpenFileDialog1.FileNames(x)
    Select Case x
        Case 0
            PictureBox1.Image = Image.FromFile(Path)
        Case 1
            PictureBox2.Image = Image.FromFile(Path)
        Case 2
            PictureBox3.Image = Image.FromFile(Path)
        Case 3
            PictureBox4.Image = Image.FromFile(Path)
    End Select
Next