In one of my applications I have an Order object which has a child object Status, I had a devil of a time figuring out how to get the Datagrid component to reference the child object when binding it to an IList of Order objects.
Example (classes chopped shorter for this example)
public class Order
{
private int orderId;
private OrderStatus status;
public int OrderId
{
get { return orderId; }
set { orderId = value; }
}
public OrderStatus Status
{
get
{
if (status == null)
status = new OrderStatus();
return status;
}
set { status = value; }
}
}
The Status object :
public class OrderStatus
{
private int orderStatusId;
private string name;
public int OrderStatusId
{
get { return orderStatusId; }
set { orderStatusId = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
In the Datagrid I had to create a ItemTemplate tag and use the DataBinder.Eval method to get the Status from the Order object by first casting the Container.DataItem to an Order object and then accessing the Status object
<asp:DataGrid id="ordersGrid" runat="server" AutoGenerateColumns="False" GridLines="Vertical"
CellPadding="3" BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#999999"
Width="552px">
<Columns>
<asp:BoundColumn DataField="OrderId" HeaderText="Order Id"></asp:BoundColumn>
<asp:BoundColumn DataField="CustomerId" HeaderText="Customer Id"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Order Status">
<ItemTemplate>
<%# DataBinder.Eval( Container.DataItem, "Status.Name") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:ButtonColumn ButtonType="LinkButton" Text="View Details" HeaderText="Options" CommandName="ViewDetails"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
The solution was quite simple but it did take some time to figure out initialy having never used Template columns or the DataBinder.
Comments