根据列表框搜索文件夹填充图片框

Search folder based on listbox to populate picturebox

我正在尝试使用文件中的列表框填充图片框。

我有以下代码(工作正常)。但是,我想保存一些编码并在文件夹中搜索与从列表框中选择的文件名匹配的文件。我已经尝试了一些不同的东西,但我对 VB 还不够流利,无法完成这项工作。任何帮助将不胜感激。

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged

    If ListBox1.SelectedItem = "test1" Then
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
        PictureBox1.Image = Image.FromFile("c:Desktop\images\test1.jpg")


    Else 
    If ListBox1.SelectedItem = "test2" Then
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
        PictureBox1.Image = Image.FromFile("c:Desktop\images\test2.jpg")
    Else
        MessageBox.Show("No Such File")
    End If
    Open_Button.Visible = True
    Open_Label.Visible = True
    Open_List.Visible = True
End Sub

如果项目的名称与您的文件名匹配,那么您可以用一个 If/Else 条件处理所有事情:

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    If ListBox1.SelectedItem IsNot Nothing Then
        Dim file = System.IO.Path.Combine("C:\YourPath\", ListBox1.SelectedItem) + ".jpg"
        If System.IO.File.Exist(file) Then
            PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
            PictureBox1.Image = Image.FromFile(file)
        Else
            MessageBox.Show("No Such File")
        End If
        Open_Button.Visible = True
        Open_Label.Visible = True
        Open_List.Visible = True
    End If
End Sub

我有!谢谢马克的帮助。

 Dim file = System.IO.Path.Combine("C:\desktop\etc\", ListBox1.SelectedItem) + ".jpg"
    If ListBox1.SelectedItem IsNot Nothing Then

        If System.IO.File.Exists(file) Then

            PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
            PictureBox1.Image = Image.FromFile(file)

        Else


            MessageBox.Show("No Image")
        End If
    End If
        Open_Button.Visible = True
        Open_Label.Visible = True
        Open_List.Visible = True
End Sub