When working with GridView and DetailsView controls, we must specify the columns we want to include, by adding field templates to the Columns and Fields collections. These field templates are bound to a specific property of a data source, which, typically, comes from a database table.
ASP.NET comes with a number of field templates (from the MSDN documentation):
|Column field type||Description|
|BoundField||Displays the value of a field in a data source as text.|
|ButtonField||Displays a command button in a data-bound control. Depending on the control, this allows you to display either a row or a column with a custom button control, such as an Add or a Remove button.|
|CheckBoxField||Displays a check box in a data-bound control. This data control field type is commonly used to display fields with a Boolean value.|
|CommandField||Displays built-in command buttons to perform edit, insert, or delete operations in a data-bound control.|
|HyperLinkField||Displays the value of a field in a data source as a hyperlink. This data control field type allows you to bind a second field to the hyperlink's URL.|
|ImageField||Displays an image in a data-bound control.|
|TemplateField||Displays user-defined content in a data-bound control according to a specified template.|
Of course, one can think of additional field templates, for example, one that would allow picking a value from another table, to which the main table is connected by a foreign key. I wrote one such template and named it ForeignKeyBoundField, and you can download the code from this post.
It must be declared, either on the DetailsView or GridView control, in the same way as a BoundField would, but with some additional properties:
<asp:DetailsView runat="server" ...> <Fields> <asp:BoundField DataField="SomeColumn" HeaderText="Some Column"/> <asp:ForeignKeyBoundField DataField="SomeOtherForeignKeyColumn" HeaderText="Some Other Column" ForeignEntityName="SomeOtherColumn" ForeignEntityDisplayField="SomeOtherDisplayColumn"/> </Fields> </asp:DetailsView>
On the ForeignKeyBoundField declaration you specify the name of an additional table which contains the column you want to display and the actual column. The two tables must be linked by the column which is equal to the content of the DataField property.
Instead of a plain text label containing the foreign key, the ForeignKeyBoundField displays the column from the associated table, and, when in edit or insert mode, displays a DropDownList allowing the selection of a value by a more meaningful column than just its id. You can see an example of th the picture below, with a DetailsView control.
In order for it to work, a SqlDataSource, LinqDataSource or EntityDataSource data source controls must be used, it won't work with ObjectDataSource, XmlDataSource or AccessDataSource.
As always, hope this comes in handy, it sure did to me!