How to access child items in a Boundfield of a Gridview in Asp.Net Web Forms?

Asked

Viewed 651 times

2

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

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

But I get a mistake trying to do that:

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

The error launched is described:

A field or Property with the name 'Meuitem.Subitem' was not found on the Selected data source.

I double-checked if I spelled the name correctly and if I need to check again. But I don’t think that’s the problem. What better means to achieve my goal?

1 answer

2


Hello,

If the idea is: a Menuitem has its properties and another item (Subitem) of the Menuitem type to form a chain 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 query.

Mode 1

Assigning datasource to gridview:

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

Within the Gridview set custom field, to access the name property:

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

Mode 2

Mount 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.

  • I think there are some errors in the code, but I understood. Thank you.

  • Thanks for the feedback André.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.