daniel_aren
daniel_aren

Reputation: 1924

work with listbox in windows form

I have trouble getting info about a selected item in a listbox in windows forms. I have a collection populated with "Persons" that have a "PersonID" and a "FirstName". I don´t want the "PersonID " to be showned in the list, only the persons name - but when i select a person from the list, how do i know what the ID is?

    public int PersonID { get; set; }
    public string FirstName { get; set; }

I know i can compare the "FirstName " in the collection but that´s not good enough if the name is the same as another persons. How do i solve this?

Upvotes: 0

Views: 391

Answers (2)

Likurg
Likurg

Reputation: 2760

Or you can use listview

listView1.Items.Add("Name").SubItems.Add("ID");

it will be more easy

Upvotes: 0

Lâm Tran Duy
Lâm Tran Duy

Reputation: 814

You can either use the DisplayMember / ValueMember properties of the ListBox control, or you can also override the ToString() method of your Person class to return the name of the person.

In this case, only the name of the person will be displayed, but calling ListBox.SelectedItem() will still return the complete Person instance.

Upvotes: 1

Related Questions