Reputation: 104
I have a listbox that i want to populate with contactpersoon objects that i created. The user completes a little form with a few textfields and when the user presses the ok button the contactpersoon object will be created.
The problem is now that i want to add the name property of the contactpersoon object to the listbox as an item. but when i want to delete it from the listbox i want to delete it by the id property of the object not the name property...
Can anyone help me with this. I tried using dictonaries but i didn't get them to work properly.
Can anyone please advise/help me with this?
Thank you very much..
BTW Iam sorry for my bad englisch :p
Upvotes: 2
Views: 5693
Reputation: 4866
While Binding to ListBox, use this -
listbox.DisplayMember = "name";
listbox.ValueMember = "id";
You can store the ID as a hidden value like this.
Upvotes: 3
Reputation: 81655
Try overriding the ToString()
function of your ContactPerson class and add the whole object to the ListBox, not just the name. The ListBox.Items
is a collection of objects, not just strings. The ToString()
is used by the ListBox control to display the text value of the object.
Alternatively, you can create a List<contactperson>
and use that as a DataSource, and just set the DisplayMember
and ValueMember
fields of the ListBox. DisplayMember
would be the visible name, the ValueMember
would be the ID field.
Upvotes: 1
Reputation: 43743
You need to override the ToString method in the ContactPerson class. For instance:
public class ContactPerson
{
public string Name;
public string Id;
public override string ToString()
{
return Name;
}
}
Then, you can add the actual ContactPerson objects to your list box. For instance:
listbox.Items.Add(contactPerson);
Then, when you delete, you can loop through each item in the list and read any of the properties of the ContactPerson object, such as:
foreach(object item in listbox.Items)
{
if((ContactPerson)item.Id == ...)
{
// do work
}
}
Upvotes: 2