Concatinating DataTextField

Is possible in c# to concatenate two fields (firstname & surname) returned from the database so that the DataTextField of a drop down list displays first name and then second name.

I have the following code but it produces errors which as far as I can see is actually looking for a record called firstnamesurname.


//Populate the employee list
employeeNameList.DataSource = reader;
employeeNameList.DataValueField = "employeeID";
employeeNameList.DataTextField = "firstname" + "Surname";
employeeNameList.DataBind();
reader.Close();

The error reads:

DataBinding: ‘System.Data.Common.DataRecordInternal’ does not contain a property with the name ‘firstnameSurname’.

Any ideas?

Morn

I think your easiest solution would be to concatinate the values in your db select statement.

ex:
select employeeid, firstname + ’ ’ + lastname as fullname from users

^^^^Please don’t do this, it kills kittens. And it pollutes your data layer.

Avoid setting the data columns in code, use ASPX templates instead. As for this case, just use a template column with a custom template:


<asp:TemplateColumn>
<ItemTemplate>
   <&#37;# DataBinder.Eval(Container.DataItem, "firstname") %>&nbsp;<%#DataBinder.Eval(Container.DataItem, "lastname") %>
</ItemTemplate>
</asp:TemplateColumn>

I haven’t tested this but it may work.

Edit:
<asp:DropDownList ID=“ddl” runat=“server” AppendDataBoundItems=“True” DataTextField=“firstname, surname” DataValueField=“userid” DataTextFormatString=“{0} {1}”>

Save the kittens!!

Unfortunatly the only way that I have got the thing to work thus far is to use the sql route.

Two questions:

  1. Why is it bad to do it that way
  2. Why can I not get the <asp:TemplateColumn> tag to display in studio?

Cheers
Morn

Uhm, mainly because I misread things–I thought it was a gridview or somesuch. Anyhow, I try and avoid codebehind like the plague, but this is one spot where it makes sense, unless you have an object layer to handle stuff like jfurman suggests. If you don’t have the object layer, you could just build the list manually by adding new ListItem objects to your list.

Oh well, the good news is that I have it working.

I will stick with the sql option.

Thanks guys

Morn