1

I have a list comprising of two other lists of custom objects that are linked by an Id. Essentially I have an 'CPDActivity' object that has many properties and an 'CPDActivityExtended' object with several more. I then have a 'CPDActivityComplete' object that contains one each of the other objects. These complete objects get added to a list which is what populates a DataTable.

I need to be able to bind this DataTable to a GridView and display the values of the properties of the CPDActivityComplete's two child objects. For example CPDActivityComplete.CPDActivity.A under an 'A' column.

Here is a basic picture of what I'm trying to do: enter image description here

The list of custom objects visualised: enter image description here

What I have tried so far:

The DataTables are populated using Entity Framework & LINQ and I have bound the GridView to the resulting DataTable:

DataTable dt = getCPDData.ToDataTable<CPDActivityComplete>(cpdActivityCompleteList);
cpd_gv_activities.DataSource = dt;
cpd_gv_activities.DataBind();

I have a simple GridView to test things out:

<asp:GridView ID="cpd_gv_activities" runat="server" AutoGenerateColumns="false" AllowPaging="True" PageSize="15">
<Columns>
    <asp:TemplateField HeaderText="Full Name">
        <ItemStyle CssClass="fixedcell"></ItemStyle>
        <ItemTemplate>
            <asp:Label ID="vd_gv_lbl_FullName" runat="server" Text='<%# Bind("CPDActivity.A") %>'></asp:Label>
        </ItemTemplate>   
    </asp:TemplateField>
</Columns>

But this results in an error:

DataBinding: 'System.String' does not contain a property with the name 'A'.

How do I bind the label.text to CPDActivityExtended.CPDActivity.A property?

1 Answer 1

2

Switch to a strongly typed GridView. Then you have easy access to all the properties and type-safety.

So first add the ItemType to the GridView

<asp:GridView ID="cpd_gv_activities" runat="server" ItemType="YourNameSpace.CPDActivityComplete">

Now you can use Item in the GridView and access properties

<asp:Label ID="vd_gv_lbl_FullName" runat="server" Text='<%# Item.A %>'></asp:Label>

And last, don't convert to a DataTable (was not needed in the first place) but bind the List with the class directly.

cpd_gv_activities.DataSource = cpdActivityCompleteList;
cpd_gv_activities.DataBind();
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Great answer, thank you! I have made the changes you suggested and everything is working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.