开发者

Determining which object was selected using a listbox

开发者 https://www.devze.com 2022-12-18 15:17 出处:网络
i have a array of objects, for example people and info about them. how could i determine who was selected in the listbox where only their first and last name is shown? Is it even possible somehow to l

i have a array of objects, for example people and info about them. how could i determine who was selected in the listbox where only their first and last name is shown? Is it even possible somehow to link a item in the listbox with a item开发者_StackOverflow in the array? Obviously i can't rely on SelectedIndex because when the names in the listbox get filtered it just doesn't work anymore.

In my application i have a listbox where are the names of persons and when i click on one person in the listbox i want to see their detais (address/contacs/misc). And the problem is when two persons share the same name.


You could use the ListBox.SelectedItem like this... If you wanted you could create a new property to concatenate the FirstName and Surname and use it as your DisplayMember

public class Person
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

var people = new[]
{
    new Person{FirstName = "Peter", Surname = "Pan"}, 
    new Person{FirstName = "Simon", Surname = "Cowell"}
};

var listbox = new ListBox
{
  DisplayMember = "FirstName",
  ValueMember = "FirstName",

  DataSource = people
};

var person = listbox.SelectedItem as Person;


I would suggest adding a unique key to your list of objects. Then you would be able to use the unique key as the value for the listitems, which you could also get when an item is selected, and which you could use to identify the item in your list of objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号