How do you bind a gridview column to a subclass value?

I have a ASP.net gridview that I am trying bind to. My DataSource has a collection and 2 of the columns I am binding to are part of a subclass. My DataSource has a subclass called Staff the contains the staff information. The boundfields SurveyID and NumberOfExceptions bind fine, but the Staff.Name and Staff.Office cannot be bound.

asp:BoundField DataField="SurveyID" HeaderText="ID" ...
asp:BoundField DataField="Staff.Name" HeaderText="Name" ...
asp:BoundField DataField="Staff.Office" HeaderText="Office" ...
asp:BoundField DataField="NumberOfExceptions" HeaderText="Exceptions" ...

And the code behind is:

uxSurveyGrid.DataSource = searchResults;
uxSurveyGrid.DataBind();

If I type searchResults[0].Staff.Name in the code behind I can see the value, why is the runtime not being able to evaluate Staff.Name in the gridview?

How do you bind the columns to the subclass values? Do I have to do it in codebehind?

Any help would be appreciated,

Mark.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I believe you can get this to work using a Template field and a markup scriptlet…

    <asp:TemplateField>
        <ItemTemplate>
            <asp:Label Id="lblSubclassVal" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "SubClass.PropertyName")%>"></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

Method 2

The data binding mechanism behind ASP.NET GridView supports only one level bindings. (as opposed to its WinForms Binding counterpart that supports multi-level in the case of binding to a DataSet / DataTable / DataView).

You have three possible solutions:

  1. Handling the ItemDataBound event for each row
  2. Extending your root level entities with properties that expose the child object properties and using these properties for the binding expressions
  3. Instead of using a BoundField you could use a Template Field and generate the content using a <%= %> expression that accesses the Data Item.

Method 3

Mark,

I am 99.9% sure that you will have to handle this in the codebehind on the ItemDataBound event for the individual row.

Remember you can get the whole databould object from e.Item.DataItem

Method 4

The [Name].[Name] syntax is not supported by BoundField. Only simple property names.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x