I was fighting with asp dropdownlist for not being able to combine two columns directly. Say I got the same scenario as the following:

Suppose you want a drop-down list to display both the first name and the last name of each employee in the company.

I should be able to use DataTextField to combine two columns like:

ddlemployeename.DataTextField = "firstname" + ', " + "lastname";

But noooo…it gives me this error:

DataBinder.Eval: ‘System.Data.DataRowView’ does not contain a property with the name firstname, lastname.

You have to go mingle with your storeprocedure or Sqlcommand statement to change the string. Then only you can set that new string to DataTextField. Something like below. Very inefficient!

There is another efficient way of adding multiple fields in Dropdownlist using DataSet and DataTable by adding a new column on fly in DataTable object.
I did tried that method, but didn’t work for me, I’ll have to try again later. Anyway that code is in page 4 of the referenced article, so you can check that out as well.

SQL Statement
SELECT lastname + ‘, ‘ + firstname AS ‘EmployeeName’
FROM Employees

Binding Code
ddlemployeename.DataTextField = “EmployeeName”;

You can use a data-binding expression to set the DataSource property. The expression you use must evaluate to a .Net object that exposes the ICollection interface. You cannot use expressions to set the other properties. The values for DataTextField and DataValueField each must match the name of one field in the data source, so you cannot assign DataTextField by combining two or more fields in the datasource.

What the hell that bold part suppose to mean? For the moment I’ll just change my storeproc for that and play around with DataTable column later.

Any of you have any better way of solving this problem please let me know.
Thanks.

Ref: Data Bound Controls (.PDF)

No related posts.