Patrick
Patrick

Reputation: 2577

Behind the scenes property of Winforms listbox item

So I'm going back and cleaning up code I did years ago. In one part, (and I used this several times) I have a list box displaying employee names such as

Smith, John Doe, Jane

When the user clicks the name, I do something like

String unBrokenName = ListBox1.SelectedItem.ToString();
String LastName = unBrokenName.Substring(...

You get the idea, I extract the first and last name based upon the ", " Then I do this to get the employee from the sql database.

Employee SelectedEmployee = Employee.GetEmployeeByFirstLast(FirstName, LastName);

At the time, it was the best I knew. Now it feels wrong, because I KNOW I should be able to get the sql ID of the employee when they select it, like

int EmployeeId = SOMELISTBOXSELECTEDITEMPROPERTY;
Employee SelectedEmployee = Employee.GetEmployeeByID(EmployeeId);

Is there some property for a listbox item that will store this id while displaying the same name the users are used to seeing?

Upvotes: 0

Views: 103

Answers (2)

Apostrofix
Apostrofix

Reputation: 2180

You can do something like this:

listBox1.DataSource = employeesList;
listBox1.DisplayMember = "LastName";
listBox1.ValueMember = "EmployeeId";

When you run your application the listbox will have the list of employees that you are passing and it will show the LastName. But when you select an item, you can access the id by:

`listBox1.SelectedValue();`

And then in the listbox1_Click event something like:

if (listBox1.SelectedIndex != -1)
{
    int employeeId = listBox1.SelectedValue();
    //do something here;       
}

Upvotes: 2

Chris
Chris

Reputation: 5514

You can actually add anything you'd like to a listbox:

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return this.Name;
    }
}

And then:

listBox1.Items.Add( new Foo() { Id = 101, Name = "Foo Bar" } );
listBox1.Items.Add( new Foo() { Id = 102, Name = "Foo Bar Jr." } );

The SelectedItem property will now give you the selected Foo, while displaying the Name property in the list itself.

private void listBox1_SelectedIndexChanged( object sender, EventArgs e )
{
    Foo item = ( listBox1.SelectedItem as Foo );
    if( item != null )
    {
        // use item.Id here
    }
}

Instead of overriding ToString, you can also use the DisplayMember property of the listbox to select which property the listbox will display.

Upvotes: 3

Related Questions