How to bind a gridview column to a subclass value?

I have an ASP.net gridview I'm trying to associate with. My DataSource has a collection and 2 of the columns that I link are part of a subclass. My DataSource has a subclass of "Staff" containing personnel information. Related fields SurveyID and NumberOfExceptions are perfectly related, but Staff.Name and Staff.Office cannot be connected.

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:

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

If I type searchResults[0].Staff.Name in the code behind, I see this value, why can't the runtime evaluate Staff.Name in gridview?

How do you bind columns to subclass values? Should I do this in code?

Any help would be appreciated

Mark.

+6
gridview
source share
4 answers

I believe that you can make this work using the Template field and layout script ...

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

The data binding engine behind ASP.NET GridView supports only one level binding. (unlike its comparison with binding to WinForms, which supports multilevel communication in the case of binding to DataSet / DataTable / DataView).

You have three possible solutions:

  • Handling an ItemDataBound event for each row
  • Extending root-level entities with properties that expose the properties of child objects and use these properties for binding expressions
  • Instead of using BoundField, you can use the Template field and generate content using the expression <% =%>, which refers to the data item.
+6
source share

Mark

I am sure that 99.9% you will have to handle this in code in the ItemDataBound event for a single line.

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

0
source share

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

0
source share

All Articles