将集合绑定到Windows窗体中的DataGridView控件

5

我正在尝试将一个集合绑定到DataGridView。但事实证明,无论EditMode是否设置为EditOnKeystrokeOrF2,用户都无法在此DataGridView中编辑任何内容。
以下是简化的代码:

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

当我将集合类型更改为SortableBindingList、Dictionary甚至使用BindingSource时,它也无法工作。这里可能出了什么问题?
3个回答

5

对我而言,以下这种方法的效果是符合预期的:

  • Open your form (usercontrol, etc.) with the designer
  • Add a BindingSource to your form
  • Select the BindingSource in your form and open the properties page
  • Select the DataSource property and click on the down arrow
  • Click on Add project data source
  • Select Object
  • Select the object type you wish to handle
    • This should be the type that will be handled by your collection, not the CustomCollection itself!
  • Show the available data sources by selecting from the MenuBar Data - Show Data Sources
  • Drag and Drop your ItemType from the DatasSources on your form
  • Go into the code of your form and bind your CustomCollection to the BindingSource

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

备注:
DataGridView只是你链中的最后一部分,用于(禁止)更改、添加和删除列表(或CustomCollection)中的对象。BindingSource中还有一个属性AllowNew,ICollection接口有一个属性IsReadOnly,必须将其设置为false才能允许编辑。最后,集合中的类的属性必须具有公共的setter方法,以允许更改值。


我已经做了你所做的事情,但是当我尝试向列表中添加新对象时,DataGridView不会刷新,尽管列表本身是正确的,并且将绑定的DataSource强制转换返回一个正确的列表。 - Bruno Machado - vargero
如果您操作了集合(添加、删除、插入、清除),那么必须通知绑定源进行更改。您可以实现IBindingList接口并在需要时引发ListChanged事件;使用BindingList<T>代替普通集合;或者调用bindingSource.ResetBindings(false)方法。 - Oliver

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

0

一旦您设置了DataSource属性,您将希望触发DataBind()方法。

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

更新:

正如你在评论中指出的那样,这个控件并不存在DataBind()方法。

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


SuppliesDataGridView 中没有这样的方法。 - Sergey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接