【问题标题】:Load images into multiple picture boxes using the same click event使用相同的点击事件将图像加载到多个图片框
【发布时间】:2015-01-06 04:54:37
【问题描述】:

我有一个包含 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 个框都没有图像,则左上角优先,如果左上角有图像,则右上角其次,依此类推。

【问题讨论】:

    标签: vb.net image


    【解决方案1】:

    另一种解决方案:

    将 OpenFileDialog 的 Multiselect 属性设置为 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
    

    【讨论】:

      【解决方案2】:

      试试类似的东西

      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
      

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

      【讨论】:

      • 你刚刚定义了两次file,不知何故你首先将它设置为一个字符串数组,而变量只是一个字符串。
      • 作为一个小提示。 :)
      【解决方案3】:

      您可以执行以下操作;只需替换名为“PBs”的数组中的图片框的名称:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多