Search code examples
asp.netgridviewboundfield

Binding objects to a Gridview


I have three classes (domain, role and user). Domain and role are properties of the user class, like this:

    public int UserID { get; set; }
    public string UserName { get; set; }
    public Domain Domain { get; set; }
    public Role Role { get; set; }
    public bool Active { get; set; }

Domain and Role just have a ID property and a Name property.

I would like to bind a user list to my grid view, but showing the DomainName. Currently, I have my bound fields like this:

<asp:BoundField DataField="Domain.DomainName" SortExpression="UserDomain" ReadOnly="True" HeaderText="User Domain" />

But this isnt working, giving the fallowing error: DataBinding: 'Yasur.Business.Entities.User' does not contain a property with the name 'DomainName'.

What is the best way to do this?

Pedro Dusso


Solution

  • I don't think you'll be able to do two-way databinding with an object like this. You can "Eval" the data if you use a TemplateField with syntax like this (not tested):

    <asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# ((Domain)Eval("Domain")).DomainName %>' />
    </ItemTemplate>