As stated by the 1st answer, the use of DisplayMember
works whether you are using asp.net or winforms.
And to comment a bit more, it also works if you are using the rather old fashion Items.add
way of adding items to a ListBox
.
Just for fun, here is a simple demo of what you need (just create a new form and drop on it a ListBox and a Label):
public partial class Form1 : Form
{
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", LastName, FirstName);
}
}
public Form1() { InitializeComponent(); }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
listBox1.DisplayMember = "LastName";
listBox1.DataSource = GetCustomers();
//listBox1.Items.AddRange(GetCustomers().ToArray());
}
private IEnumerable<Customer> GetCustomers()
{
return new List<Customer>()
{
new Customer() { FirstName = "Gustav", LastName = "MAHLER" },
new Customer() { FirstName = "Johann Sebastian", LastName = "BACH" }
};
}
private void lb_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedItem.ToString();
}
}
Enjoy
PS: @2nd post Tag
is not available to ListBox
: because it accepts an array of object
, not a specific item container like ListView
... but you don't need any in your case. Tag
is useful when you want to carry additional data along with a specific TreeViewItem
or ListViewItem
for example.
By the way, Tag
is defined at the Control
level and so exists for Button
, Label
, and so on... but for my part I think it is rather a bad idea to store business data in it (untyped, UI coupled...) apart from the ListView
and TreeView
cases for which it is rather convenient.