简体   繁体   中英

Binding List of Object to DataGrid

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM