Hi,
Sorry the title is a bit vague, I didn't know how to describe it.
The problem is very simple actually: I have a class Person that represents a person in my database. This class has a CategoryId property (int) and a Category property (type Category).
Category is a class that represents a category in my database.
csharp Code:
public class Person
{
public int Id {get; set;}
public string Firstname {get; set;}
public string Lastname {get; set;}
public int CategoryId {get; set;}
public Category Category {get; set;}
}
public class Category
{
public int Id {get; set;}
public string CategoryName {get; set;}
}
I am displaying a list of these Persons in a GridView, and I would like to display the name of the Category (the CategoryName property to be precise). So I define this markup;
xml Code:
<asp:GridView runat="server" ID="personsGrid" AutoGenerateSelectButton="True"
AutoGenerateColumns="False" DataKeyNames="Id">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="Lastname" HeaderText="Lastname" />
<asp:BoundField DataField="Category" HeaderText="Category" />
</Columns>
</asp:GridView>
While this works, the Category column obviously does not display the name of the category, but rather the type name (ProjectName.Category).
Usually I would solve this problem by one of two ways:
- Override the ToString method of the Category class and return the name.
- Add a readonly 'CategoryName' property to the Person class, where I return 'this.Category.CategoryName' (and then bind the column to this property instead).
In this case however, I am using the Entity Framework, and the Person and Category classes are automatically generated by the database model. I suppose I could edit the generated code manually, but I don't like that, since any change in the model will cause VS to re-generate the code and my changes would be lost. So these two methods are not going to work...
The simple question remains: how do I make the Category column show the CategoryName property of the object it represents, rather than just the type name?
In a DropdownList for example (which I am already using for the user to select a category when creating a person), I can set the DataTextField (to "CategoryName") and DataValueField (to "Id") properties and it displays the right name and uses the right value (the Id). I can't find anything similar for a BoundField though... Am I overlooking something obvious?
Another solution would be if I could tell the Entity Framework model to add another property to my Person class which returns the CategoryName of the Category. I can't find any way to do that though (I am a compleet noob in EF), so if anyone happens to know how to do that, that would work equally well 
Thanks!