Combining Two DataSource Fields Into One DataGrid Column
By: Scott Mitchell | Created: 2003-05-09 | Last Updated: 2003-05-15



Imagine that you have a database table called Employees which has the following fields:

You may want to display a list of the employees and the various attributes in a DataGrid. However, instead of having a column for both the employee's first and last name, you would like to have one DataGrid column titled "Name" that displays their last name, followed by a comma, followed by their first name.

Usually, when displaying fields from the DataSource, we simply use a BoundColumn, with the BoundColumn's DataField property set to the DataSource field to display. However, we have two DataSource fields we want to display - how can we do this?

We can apply one of the following two techniques to surmount this problem:

  1. Adjust our SQL statement so that it combines both fields into a single field, and then specify this synthetic field in the BoundColumn's DataField property, or
  2. Use a TemplateColumn with both fields displayed using data-binding syntax.

Option 1: Adjusting the SQL Statement
In SQL, you can concatenate two string (varchar, char, etc.) fields using the + operator. You can give a name to a column by using the AS keyword. So, to create (and name) a column that contains the employee's last name, followed by a comma, followed by their first name, we can use the following SQL statement:

SELECT ..., LastName + ', ' + FirstName AS FullName, ... FROM Employees

This new field is called FullName. To display it, we can add a BoundColumn to our DataGrid with its DataField property set to FullName.

Option 2: Using a TemplateColumn
The second option for tackling this problem is to use a TemplateColumn and explicitly display both fields using the data-binding syntax. Here, I am assuming you are using a SQL statement that does not have the FullName synthetic field. That is, I'm assuming the SQL statement to populate the DataGrid looks like:

SELECT ..., LastName, FirstName, ... FROM Employees

Now, to display the last name, followed by a comma, followed by the first name, we simply add a TemplateColumn and specify the output we're after in the ItemTemplate like so:

<asp:DataGrid runat="server" AutoGenerateColumns="False" ...> <Columns> <asp:TemplateColumn HeaderText="Name"> <ItemTemplate> <%# Container.DataItem("LastName") %>, <%# Container.DataItem("FirstName") %> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid>

That's all there is to it!


Home | FAQs | Articles | About | Buy the Book!

Copyright 2006, Scott Mitchell. All Rights Reserved.