Reputation: 1020
I'm trying to bind a list of objects to a DataGrid on the compact framework. This is what I have:
public class Order
{
//Other stuff
public Customer Customer
{
get { return _customer; }
}
}
public class Customer
{
//Other stuff
public string Address
{
get { return _address; }
}
}
Now I want to bind the DataGrid to a list of Order and display only certain properties (the customer's address is one of them):
List<Order> orders = MethodThatGetsOrders();
datagrid.DataSource = orders;
datagrid.TableStyles.Clear();
DataGridTableStyle ts = new DataGridTableStyle();
ts.MappingName = orders.GetType().Name; //This works OK
DataGridTextBoxColumn tb = new DataGridTextBoxColumn();
tb.MappingName = orders.GetType().GetProperty("Customer").GetType().GetProperty("Address").Name; //Throws NullRef
ts.GridColumnStyles.Add(tb);
datagrid.TableStyles.Add(ts);
How can I display the customer's address on the DataGridTextBoxColumn?
Thanks
Upvotes: 0
Views: 850
Reputation: 4692
I would form a viewmodel (or better an adapter) before having to mess around with bindings and get a flat model you can bind easily to:
public class OrderViewModel
{
private Order _order;
public string Address
{
get { return _order.Customer.Address; }
}
// similar with other properties
public OrderViewModel(Order order)
{
_order = order;
}
}
To generate the ViewModelList do:
List<OrderViewModel> viewModels = yourList.Select(m=> new OrderViewModel(m)).ToList();
And to bind simply:
YourGridView.Datasource = new BindingSource(viewModels, null);
Upvotes: 2