How to access child items in a BoundField of a GridView in Asp.Net Web Forms?

2

I know that in the middle of GridView , you can read an immediate item with the tag BoundField :

<asp:BoundField DataField="MeuItem" HeaderText="Meu item" />

But I get an error trying to do this:

<asp:BoundField DataField="MeuItem.SubItem" HeaderText="Meu sub item" />

The error posted describes:

  

A field or property with the name 'MyItem.SubItem' was not found on the selected data source.

I've checked twice if I've spelled the name correctly and if I need Czech again. But I do not think that's the problem. What is the best way to achieve my goal?

    
asked by anonymous 18.02.2014 / 20:34

1 answer

2

Hello,

If the idea is: a MenuItem has its properties and another item (SubItem) of type MenuItem to form a thread or auto reference:

public class MenuItem { 
string Nome { get; set; }
MenuItem SubItem { get; set; }
}

You can do this in two ways, the first is to access the property of the child object via cast. The second is at the time of the query.

Mode 1

Assigning the datasource to the gridview:

var MenuItens = contexto.MenuItem;
GridView1.DataSource = MenuItens.ToList();
GridView1.DataBind();

Within the GridView define custom field, to access the name property:

<asp:TemplateField>
    <ItemTemplate>
        <span>string.Format("{0}", ((MenuItem)Eval("SubItem")).Nome)</span>
    </ItemTemplate>
</asp:TemplateField>

Mode 2

Build your data source the way you need it directly in the query:

var MenuItens = contexto.MenuItem.Select(m => new
{ 
    Nome = m.Nome,
    SubItem = m.SubItem.Nome
});
GridView1.DataSource = MenuItens.ToList();
GridView1.DataBind();

In GridView just access as follows:

<asp:BoundField DataField="SubItem" HeaderText="SubItem" />

I hope you can understand. Good Luck.

    
19.02.2014 / 04:36