deltu100
deltu100

Reputation: 581

Send data to checkedlistbox

I have a query with a list of names that I put into a checkedlistbox. But I also want to send my table key with it. But at the same time I don't want to show it.

current code:

        Dim Querynames = (From rec In db.table
                         Select rec.tableKey, rec.Names).ToList

        For Each item In Querynames 
          'Need to send my table key with each name
            CheckedListBox1.Items.Add(item.Names)
        Next

I will be using this table key to query a search. What I would like to prevent is to make a second Linq.

How do I send "hidden" data(which will be the table key) with my checkedlistbox, so I can reach the key from code?

Upvotes: 1

Views: 1225

Answers (1)

sloth
sloth

Reputation: 101072

You should add the entire objects to the CheckedListBox, not only the Names.

For Each item In Querynames 
    CheckedListBox1.Items.Add(item)
Next

Then you should set the DisplayMember property.

CheckedListBox1.DisplayMember = "Names"

so the CheckedListBox will just display the Names property.

You probably want to use a regular class instead of an anonymous type, so you can cast the items back to access the tableKey property.


Consider the following example:

Sub Main
    Dim clb = new System.Windows.Forms.CheckedListBox()

    Dim f = new System.Windows.Forms.Form()
    f.Controls.Add(clb)

    Dim items = new Item() { new Item() with {.TableKey = "Foo", .Names = "Foobar"},
                             new Item() with {.TableKey = "ABC", .Names = "ABCDEFG"}}

    For Each item in items
        clb.Items.Add(item)
    next

    clb.DisplayMember = "Names"

    f.ShowDialog()

    Dim message = String.Join(" and ", clb.CheckedItems.Cast(Of Item).Select(Function(i) i.TableKey))
    System.Windows.Forms.MessageBox.Show(message)
End Sub

Class Item
    Public Property TableKey As String 
    Public Property Names As String 
End Class

Another way would be to just store your query result in an Dictionary and later just look up the Names <-> tableKey pair.

Upvotes: 1

Related Questions