Need help on combo box and picture box

todoink

Member
Joined
Jul 27, 2006
Messages
15
Programming Experience
Beginner
Hi, as a continuation on my mini project, how can I possible make a picture change everytime I select an item on the combo box? Let's say my combo box contents includes (as texts) my birthday picture and my vacation picture, when I select "my birthday picture", then the picture box will show a picture taken during my birthday. And same with my vacation. Thanks and more thanks.
 
Hi,
if you pictures are in the currentworkingdirectory then you may populate the combobox as follows

VB.NET:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each picture As String In System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory(), "*.jpg")
            Me.ComboBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(picture))
        Next
    End Sub

and in the ComboBox1_SelectedIndexChanged set the image

VB.NET:
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim filePath As String = System.IO.Directory.GetCurrentDirectory() & "\" & ComboBox1.Text & ".jpg"
        Me.PictureBox1.Image = Bitmap.FromFile(filePath)
    End Sub
 
Hi,
if you pictures ...snip...


It would actually make more sense to use a datatable or custome class for your list items:

VB.NET:
  Friend Class ComboPicItem
    Public Path as String
    Public Sub New(picPath as String)
      path= picPath
    End SUb

    Public Overrides Function ToString() As String
      Return IO.Path.GetFileNameWithoutExtension(path)
    End Function
  End Class

Put that at the end of your form class file, just after the "End Class" that relates to the form class


When you make your combo list:

VB.NET:
For Each picPath As String In System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory(), "*.jpg")
            Me.ComboBox1.Items.Add([B]New ComboPicItem(picPath)[/B])
        Next

Now whatever shows in the combo list, is what is returned by ToString().. if you want to include the size in the combo, put it in the ToString:

Return IO.Path.GetFileNameWithoutExtension(path) & IO.File.GetLength(picPath)

Or whatever


When the user chooses some item, use the SelectedItemCHanged event..

The combo.SelectedItem will return you a ComboPicItem object, so cast it and get the path:

VB.NET:
Combo_SelectedItemCHanged(...) Handles combo.SelectedItemChanged

  MessageBox.Show("You chose " & [B]DirectCast(combo.SelectedItem, ComboPicItem)[/B].Path )

That's more like proper OO programming.. ;)
 
Back
Top