2010-04-25 52 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

相关问题