Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET CheckedListBox Tag?

Is there a Tag for an Item in the CheckedListBox? Or something similar? I would like to be able to store and ID associated with the item that I'm displaying.

like image 894
Alex Avatar asked Jan 22 '23 14:01

Alex


1 Answers

You don't need a Tag property. The control accepts any object, that means you don't have to put just strings in it. Make a class that has a string (and overrridden ToString()) and any other data members you need.

Public Class Form1

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)

        CheckedListBox1.Items.Add(New MyListBoxItem() With {.Name = "One", .ExtraData = "extra 1"})
        CheckedListBox1.Items.Add(New MyListBoxItem() With {.Name = "Two", .ExtraData = "extra 2"})
    End Sub

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        For Each obj As Object In CheckedListBox1.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            MessageBox.Show(String.Format("{0}/{1} is checked.", item.Name, item.ExtraData))
        Next
    End Sub
End Class

Public Class MyListBoxItem
    Private _name As String
    Private _extraData As String

    Public Property Name As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Property ExtraData As String
        Get
            Return _extraData
        End Get
        Set(ByVal value As String)
            _extraData = value
        End Set
    End Property

    Public Overrides Function ToString() As String
        Return Name
    End Function

End Class

(The overridden ToString() dictates what will be displayed in the box.)

like image 109
OwenP Avatar answered Feb 02 '23 07:02

OwenP