Tuesday, April 14, 2009

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:

   1:  ddlUsers.DataSource = BLL.Employee.GetEmployees()
   2:                  .Select(be => 
   3:                      new { 
   4:                          ID = be.Id, 
   5:                          FullName = String.Format("{0}{1}{2}", 
   6:                                      be.LastName,
   7:                                      (!string.IsNullOrEmpty(be.FirstName) ? ", " : string.Empty),
   8:                                      be.FirstName)
   9:                          }).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.

No comments:

Archive