Muhnamana
Muhnamana

Reputation: 1044

Listbox Items Name Linked To Another Control

So the following code is adding a picturebox for each item that has been entered into a listbox.

    Dim x As Integer = 790
    Dim y As Integer = 91
    For i As Integer = 0 To ListBox1.Items.Count - 1

        'adds picturebox for as many listbox items added
        Dim MyPictureBox As New PictureBox()
        MyPictureBox.Location = New Point(x, y)
        MyPictureBox.Size = New Size(12, 12)
        MyPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
        Me.Controls.Add(MyPictureBox)
        MyPictureBox.Image = My.Resources.Warning1
        x += 0
        y += 13

    Next i

I have another process running that will create a file for each item in the listbox and have that file named for each item.

Exampe: I added 20 items to the listbox and I'll have 20 pictureboxes. If I want to remove say item 15, I also want to remove the picturebox next to it.

Can this be done?

Upvotes: 0

Views: 642

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

If the text of the ListBox items are unique, then you can use that to link the two together, otherwise, you'll need some other property on each item which can be used as a unique key. What you can then do is to set the Name property of each PictureBox control to the unique key value of the matching item in the list. For instance:

Dim key As String = ListBoxItems(i).ToString()
...
MyPictureBox.Name = "pic" + key

Then, when you want to get the matching PictureBox control for a given item, you could do something like this:

Dim p As PictureBox = CType(Me.Controls("pic" + item.ToString()), PictureBox)

(Where item is the item from the ListBox) To delete it, you would just do this:

Me.Controls.Remove(p)
p.Dispose()

Upvotes: 1

Related Questions