Listbox Control (ugh) Multiple Names?

Good, so the name was awful. I know it. Here is what I am trying to do:

I have a lot of data that comes from the database and is added to the list. Data coming from the database is a unique identifier and name.

Is there a way to make an element contain both ID and name? I know that I can add it, this is not what I am looking for. I need a way to get an identifier or get a name by showing both of them.

I got to creating a class:

Class Item Property ID as Integer Property Name as String Sub New(ID as Integer, Name as String) Me.ID = ID Me.Name = Name End Sub Overrides Function ToString() as String Return Name End Function End Class 

It looks like he should do the trick, but I can’t get the identifier, not the name. Simply put, I would like to do this: listbox1.selecteditem (id) to get the identifier or listbox1.selecteditem (name) to get the name.

Please, help!

+4
source share
2 answers

You can bind to a List(Of Item) as follows:

 Dim ItemList = New List(Of Item) ' Fill the list with appropiate values.' listbox1.DataSource = ItemList listbox1.DisplayMember = "Name" listbox1.ValueMember = "ID" 

Then listbox1.SelectedValue contains the ID , and you can access this name:

 DirectCast(listbox1.SelectedItem, Item).Name 

If you want to show both ID and Name , I suggest you add a property displayed in the Item class:

 Public ReadOnly Property DisplayedValue() as String Get Return Me.Name & " (" & Me.ID.ToString & ")" End Get End Property 

Then when linking the make list

  listbox1.DisplayMember = "DisplayedValue" 

Update:

Based on your comments below, I would say that my solution still works. However, using this methodology, items must be added to the list, and then the list associated with the object. Elements cannot be added separately and directly to the list box (since you will separate data from the presentation, I do not see a problem in this).

To display a message box with the selected item, you just need to do:

 MessageBox.Show(DirectCast(listbox1.SelectedItem, Item).ID.ToString)) 
+3
source

I think you will have to write a helper method for this. If you are using VB 3.5 or later (part of VS2008 and later), you can write an extension method so that you can at least get a good syntax. You can write one so that it looks like this:

 listbox1.SelectByID(123) listbox1.SelectByName("hello") 

In the methods you will have some kind of search algorithm that went through the elements and found the right one.

0
source

Source: https://habr.com/ru/post/1301073/


All Articles