How to associate a ListBox with a property of type List on an object?

I have a form with a DataGridView showing a list of clients and some text fields below showing details of the client selected in the grid.

I have a Customer class and a CustomerList class of Customer objects, and the BindingSource with DataSource is set to CustomerList. The mesh data source is this BindingSource.

Linking text fields is very simple - I just use the same BindingSource and specify the Customer property that I want to display. The problem is that one of the properties of the Client is the list itself, and I want to display this list, for example. Listbox

How can I show this list in a ListBox using data binding and update the list every time I click on a client in the grid?

+3
source share
2 answers

You can use related BindingSource. A complete example is given below, but the only interesting bit:

        BindingSource outer = new BindingSource(customers, ""),
            inner = new BindingSource(outer, "Orders");

here is the code:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
class Order
{
    public string OrderRef { get; set; }
    public override string ToString() {
        return OrderRef;
    }
}
class Customer
{
    public string Name {get;set;}
    public Customer() { Orders = new List<Order>(); }
    public List<Order> Orders { get; private set; }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        List<Customer> customers = new List<Customer> {
            new Customer {Name = "Fred", Orders = {
                new Order { OrderRef = "ab112"},
                new Order { OrderRef = "ab113"}
            }},
            new Customer {Name = "Barney", Orders = {
                new Order { OrderRef = "ab114"}
            }},
        };
        BindingSource outer = new BindingSource(customers, ""),
            inner = new BindingSource(outer, "Orders");
        Application.Run(new Form
        {
            Controls =
            {
                new DataGridView {
                    Dock = DockStyle.Fill,
                    DataSource = outer},
                new ListBox {
                    Dock = DockStyle.Right,
                    DataSource = inner
                }
            }
        });
    }
}
+5
source

I assume the property is a list of strings.

All you need to do, as for the text, follow these steps:

listBox1.DataSource = ListOfProperties;

Just change the List as the client changes. If you post the code, it will be easier for you to find out what the real problem is.

0
source

Source: https://habr.com/ru/post/1711721/


All Articles