Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can some please help me?

I want to add items to a listbox during runtime (i know how to do this). But i want to add tag(numerical tag) to each items that i add. Is that possible (without using data binding)? So when the user click the item in the listbox i can read the numberical tag. I know i can read string of item user selected but i think tag would be better.

i am using vb.net windows application
Posted
Comments
Sergey Alexandrovich Kryukov 11-Dec-13 16:17pm    
Yes.
—SA
Member 8525993 11-Dec-13 16:23pm    
Could you please give me a example ? if i add two item how would i determine tag after users selected that item.

or refer me to site that has good exams?
ZurdoDev 11-Dec-13 16:25pm    
Just from memory, you need to create a ListBoxItem first and set Value and Text. Then add that item to the ListBox. You can't do it directly using ListBox.Items.Add()
Member 8525993 11-Dec-13 16:58pm    
Could you please tell me how exactly do you do that?

I know you can do that with listview but i am not sure how to do that with listbox.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' ListBox()

ListView1.Columns.Add("MyHeader", ListView1.Width)
ListView1.View = View.Details
Dim lv As New ListViewItem
lv.Text = "Fourty Five"
lv.Tag = 45
ListView1.Items.Add(lv)

Dim lv2 As New ListViewItem
lv2.Text = "Fourty six"
lv2.Tag = 46
ListView1.Items.Add(lv2)

End Sub
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
MessageBox.Show(ListView1.FocusedItem.Text & "=" & ListView1.FocusedItem.Tag.ToString)
End Sub
ZurdoDev 11-Dec-13 17:03pm    
Again, this is from memory but create a new instance of ListBoxItem

ListBoxItem temp = new ListBoxItem();
temp.Value="tag";
temp.Text="text";
ListBox.Items.Add(temp);

1 solution

Instead of 'adding a tag on each item' you might fill the listbox with objects containig the tag too (since listbox items are objects).
For instance, suppose your original listbox contains strings, then you could create a Class, say MyData, having two properties: the string and the tag. Then you might fill the listbox with instances (objects) of MyData Class. Hence every item would contain both the original string and the numeric tag.
 
Share this answer
 
Comments
Idle_Force 12-Dec-13 0:01am    
You have to Override the ToString() function so the ListBox knows what to display.
CPallini 12-Dec-13 3:31am    
Yes, you are rigth.
CPallini 12-Dec-13 10:54am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900