Displaying multiple fields in a Dropdownlist’s DataTextField

I’ve encountered this problem on occasion, where I want to display more than one field in a dropdownlist’s DataTextField property. In the past, I’ve overcome this problem by rewriting a SQL statement, or adding another column in the database itself to accomodate my needs.

In one of my classes (INFO 465: Projects in Information Systems @ VCU), we’re working from a database which we’re not allowed to change. The reason we can’t change it is because the instructor uses the same database for his examples. I could just write another method into my business logic layer, but it would get cluttered pretty quickly.

So, I decided to make use of LINQ and found the following solution:

ddlUsers.DataSource = BLL.Employee.GetEmployees()
                  .Select(be => 
                      new { 
                          ID = be.Id, 
                          FullName = String.Format("{0}{1}{2}", 
                                      be.LastName,
                                      (!string.IsNullOrEmpty(be.FirstName) ? ", " : string.Empty),
                                      be.FirstName)
                          }).AsEnumerable();

This takes the List of Business Entity objects and uses the LINQ select statement to generate an implicit/anonymous object from that. The only downfall to this method is that the new object only has local scope. But, since I’m only using this in a dropdown, it’s a pretty nifty trick.

Related Articles