Imagine that you have a database table called Employees which has the following fields:
EmployeeID - the employee's IDFirstName - the employee's first nameLastName - the employee's last nameYou 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:
DataField property, or
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:
|
|
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:
|
|
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:
|
|
That's all there is to it!
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.