
When binding a DataTable to a GridView, I always map every column in the DataTable to a new column in GridView (whether it be manually or automatic). I would then hide the columns I did not want to display. In this way, I could still access values in the hidden columns on GridView events such as RowDataBound. A common example of this situation is creating a hidden column for the row’s unique database id.
Since then, I have learned usage practices for a DataKey, which is native to the GridView control. In a high level overview of a DataKey, we simply specify the names of a DataTable’s columns (in which we originally wanted to hide in a GridView) in a comma separated list. The values can then be accessed via the GridView.
For a concrete example, let us assume we have the following information retrieved from a database. The column name id is our primary key from the database:
| id |
firstName |
lastName |
age |
gender |
| 1 |
Victor |
Chen |
23 |
M |
| 2 |
John |
Doe |
26 |
M |
| 3 |
Jane |
Smith |
19 |
F |
| 4 |
Mary |
Ann |
35 |
F |
We only want to display on the GridView a firstName, lastName, and gender. However, during GridView events, we still want access to the id and age. To setup the GridView, it only takes 3 easy steps!
- Place a GridView control on your aspx page.
- Manually setup visible columns for firstName, lastName, and gender. (A tutorial on this step)
- In the GridView properties and find DataKeyNames (There is an image on what this looks like at the top of this tutorial). Insert a comma separated list for that property: id,age
Now, when you compile and run the page, you will see your GridView is populated with 3 columns. Now to access the hidden values id and age only takes an if statement and one line per hidden column! We will access these values on the RowDataBound event:
protected void gvTemplate_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowIndex = e.Row.DataItemIndex;
int id = Convert.ToInt32(gvTemplate.DataKeys[rowIndex].Values["id"]);
int age = Convert.ToInt32(gvTemplate.DataKeys[rowIndex].Values["age"]);
}
}
In our example above, gvTemplate is the name of our GridView. We access the DataKeys property and specifically access the rowIndex of interest. Because we specified two items id and age in the GridView, we can access them by name. You can also access it by index, but using the actual index’s name makes the code more readable. The final step in the line is to convert the object into the variable type of your choice. If you want, you can shorthand the code with:
gvTemplate.DataKeys[rowIndex]["age"]
You will still need to convert the object into the variable type of your choice. In this case, the best choice is to convert an age it into a integer. And there we have it! We have successfully created a GridView without hidden columns, but still accessible hidden values!