2010-04-25 64 views
5

我試圖將集合綁定到DataGridView。事實證明,用戶無法編輯此DataGridView中的任何內容,但EditMode設置爲EditOnKeystrokeOrF2。
這裏是簡化代碼:將集合綁定到Windows窗體中的DataGridView

public Supplies() 
{ 
    InitializeComponent(); 
    List<string> l = new <string>(); 
    l.Add("hello"); 
    this.SuppliesDataGridView.DataSource = l; 
} 

它也不會在工作的時候改變集合類型SortableBindingList,字典,甚至使用的BindingSource。

這裏有什麼問題?

回答

0

一旦你設置了數據源屬性,你就會想要觸發 DataBind()方法。

this.SuppliesDataGridView.DataSource = l; 
this.SuppliesDataGridView.DataBind(); 

UPDATE:

正如你正確地在評論中指出,該的DataBind()方法不存在此控件。

此鏈接可能會提供一些有用的信息:http://msdn.microsoft.com/en-us/library/fbk67b6z%28v=VS.90%29.aspx

+0

SuppliesDataGridView中沒有這樣的方法。 – Sergey 2010-04-25 12:16:49

2

試試這個:

public class CustomCollection { public string Value { get; set; } } 

    public Supplies() 
    { 
     InitializeComponent(); 
     List<CustomCollection> l = new List<CustomCollection> { new CustomCollection { Value = "hello" } }; 
     this.SuppliesDataGridView.DataSource = l; 
    } 
5

對我來說,下面的方法按預期工作:

  • 打開表單(用戶控件等。 )與設計師聯繫
  • 將BindingSource添加到您的表單
  • 在窗體中選擇的BindingSource並打開屬性頁
  • 選擇DataSource屬性,點擊向下箭頭
  • 點擊添加項目數據源
  • 選擇對象
  • 選擇對象您想要處理的類型
    • 這應該是您的集合將處理的類型,而不是CustomCollection本身!
  • 從菜單欄數據選擇顯示可用的數據源 - 顯示數據源
  • 將它從DatasSources表單
  • 去放下你的ItemType到您的形式和綁定的代碼您的CustomCollection到BindingSource

    var cc = new CustomCollection(); 
        bindingSource1.DataSource = cc; 
    

備註
DataGridView只是您鏈(dis)允許更改,添加和刪除列表中的對象(或CustomCollection)的最後一部分。BindingSource中還有一個AllowNew屬性,ICollection接口的屬性IsReadOnly必須設置爲false以允許編輯。最後但並非最不重要的是,集合中類的屬性必須具有公共setter方法,以允許更改值。

+0

我已經完成了你所做的事情,但是當我嘗試向列表中添加新對象時,DataGridView不會刷新,儘管列表本身是正確的,並且轉換綁定的DataSource也會返回正確的列表。 – 2012-07-31 01:41:38

+0

如果您操作集合(添加,刪除,插入,清除),則必須通知綁定源有關該更改。要麼實現'IBindingList'並在需要時引發ListChanged事件;使用'BindingList '而不是你的普通集合,或者你調用'bindingSource.ResetBindings(false)' – Oliver 2012-07-31 09:05:10

相關問題