Michael
Michael

Reputation: 8739

Populating a ListBox with List<Entity>

I am using LINQ to Entites in my WindowsForm application.

I am trying to populate a Lisbox with the result of a query:

So my datasource is a List where User is a table in my database and a EntityType in my model.

The problem is I want the Displaymember to bea concat of 3 different Columns. (User.Firstname + " " + user.LastName + " - " + user.userCode)

and ValueMember to be user.ID;

I could just create a struct of a userItem with the 4 items, iterate through the list of User's and add them to another List. But this seems like double processing.

Upvotes: 0

Views: 1245

Answers (2)

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can extend the Entity in the partial class with a custom property like this:

public partial class User
{
    public string Description
    {
        get
        {
             return string.Format("{0} {1} - {2}", FirstName, LastName, UserCode);
        }
    }
}

If you don't want to add the property you can also use a Linq Projection to create a custom list with the computed property:

var listdata = (from u in Users
                select new
                {
                   Description = string.Format("{0} {1} - {2}", u.FirstName, u.LastName, u.UserCode).
                   Id = u.Id;    
                }.ToList();

Then you can bind listdata to your listbox.

Upvotes: 3

Haris Hasan
Haris Hasan

Reputation: 30097

Why don't you just create a property in your model which returns the concatenated value from three columns/properties. Then set the DisplayMemeber equal to that property

Another way could be to add a Computed Columns in your table. Combine the value of rest of the columns through expression

Upvotes: 2

Related Questions