One of the many benefits of the DataGrid is the ease with which you can have the contents of a database table displayed. For example, to display the contents of a database column, you can simply use a BoundColumn with its DataField property set to the name of the database field whose value you want to appear in the column.
However, what if you find that the value in the database field is not the precise value you want displayed?
For example, imagine that you wanted to display a database table named Employees that had the
following fields:
Name - the employee's nameSalary - the employee's salaryGender - the employee's genderPerhaps the value of the Gender field was either an M for male, or F for
female. Rather than display "M" or "F" in the DataGrid, you want to display "Male" or "Female." To accomplish this
we will use a TemplateColumn whose ItemTemplate calls a DataGrid helper function.
A DataGrid helper function is a function that is used in a TemplateColumn and takes in an arbitrary number of parameters and returns a string. The string returned by the function is what is displayed in the TemplateColumn. For our example, our helper function will take in one parameter - the gener of the employee - and return a string: either "Male" or "Female", depending upon the value passed in.
First, let's create our helper function, and then we'll look at how to have it called from the DataGrid's TemplateColumn. The following function accepts a string input and returns the appropriate gender string:
|
|
| VB.NET |
|
|
| C# |
| Examining the C# Version of PrintGender()... |
You may be wondering why, in the C# example, the gender input parameter is of type object, instead of type string.
This is because when calling the PrintGender, the results of Container.DataItem("Gender") will
be passed in. This returns an object. VB.NET, by default, will automatically convert the object being inputted into a
string. C#, however, will not do this, so we must accept an object as the parameter, and then cast it to a string.
|
Now, we need to see how to call this DataGrid helper function from our TemplateColumn. Essentially, you have to use DataBinding
syntax to call the function, passing in the value of the DataSource's Gender field. Our DataGrid's
declaration would look something like:
|
|
| VB.NET |
That's all there is to it!
| <shameless plug> |
| Curious as to how you can create a DataGrid helper function that can display different messages based on whether the field value is NULL? For information on this, check out the "Handling NULL Database Values" section in Chapter 3. (Chapter 3 is available online for free!) |
| </shameless plug> |
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.