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

Ser*_*gey 5 c# datagridview winforms

我正在尝试将集合绑定到DataGridView.事实证明,虽然EditMode设置为EditOnKeystrokeOrF2,但用户无法在此DataGridView中编辑任何内容.
这是简化的代码:

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

当我将集合类型更改为SortableBindingList,Dictionary或甚至使用BindingSource时,它也不起作用.

这可能有什么不对?

Oli*_*ver 5

对我来说,以下方法按预期工作:

  • 使用设计器打开表单(usercontrol等)
  • 将BindingSource添加到表单
  • 在表单中选择BindingSource并打开属性页面
  • 选择DataSource属性,然后单击向下箭头
  • 单击" 添加项目数据源"
  • 选择对象
  • 选择要处理的对象类型
    • 这应该是您的集合将处理的类型,而不是CustomCollection本身!
  • 通过从MenuBar 数据 - 显示数据源中进行选择来显示可用的数据源
  • 从表单上的DatasSources拖放ItemType
  • 进入表单的代码并将CustomCollection绑定到BindingSource

        var cc = new CustomCollection();
        bindingSource1.DataSource = cc;
    
    Run Code Online (Sandbox Code Playgroud)

备注:
DataGridView只是链中允许更改,添加和删除列表中的对象(或CustomCollection)的最后一部分.AllowNewBindingSource中还有一个属性,该ICollection接口具有IsReadOnly必须设置false为允许编辑的属性.最后但同样重要的是,集合中类的属性必须具有允许更改值的公共setter方法.


Jam*_*xon 0

设置 DataSource 属性后,您将需要触发该DataBind()方法。

this.SuppliesDataGridView.DataSource = l;
this.SuppliesDataGridView.DataBind();
Run Code Online (Sandbox Code Playgroud)

更新:

正如您在注释中正确指出的那样,该控件不存在 DataBind() 方法。

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