基于列表框搜索文件夹以填充图片框

时间:2016-11-26 18:22:52

标签: vb.net listbox 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

2 个答案:

答案 0 :(得分:1)

如果项目的名称与您的文件名匹配,那么您可以使用单个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

答案 1 :(得分:0)

我拥有它!谢谢Marc的帮助。

 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