2009-07-02 105 views
3

我有一個DataGridView顯示客戶列表的表單,下面的一些文本框顯示了在網格中選擇的客戶的詳細信息。如何將ListBox綁定到對象上List類型的屬性?

我有一個Customer類和一個CustomerList類的Customer對象,而一個BindingSource的DataSource被設置爲一個CustomerList。網格的DataSource就是這個BindingSource。

綁定文本框很簡單 - 我只是使用相同的BindingSource並指定要顯示的Customer的屬性。問題是客戶的其中一個屬性本身就是一個列表,我想要在例如一個ListBox。

我該如何使用數據綁定來完成在ListBox中顯示此列表,並且每次點擊網格中的客戶時都更新列表?

回答

5

您可以使用鏈接的BindingSource。一個完整的例子如下,但唯一有趣的一點是:

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

下面的代碼:

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 
       } 
      } 
     }); 
    } 
} 
+0

用於創建表單的不錯的簡約方法。 – VVS 2009-07-02 07:53:36

0

我認爲財產是一個字符串列表。

所有你需要做的像你一樣的文字,這樣做:

listBox1.DataSource = ListOfProperties; 

只要改變列表作爲客戶的變化。 如果您發佈代碼,將更容易知道真正的問題。

相關問題