C# 如何将数组正确绑定到datagridview?

C# 如何将数组正确绑定到datagridview?,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,有一个具有某些属性的依赖类 class Dependency: { public string ArtifactId { get; set; } public string GroupId { get; set; } public string Version { get; set; } public Dependency() {} } 和ProjectView类: class ProjectView: { public string D

有一个具有某些属性的依赖类

class Dependency:
{
     public string ArtifactId { get; set; }
     public string GroupId { get; set; }
     public string Version { get; set; }

     public Dependency() {}
}
和ProjectView类:

 class ProjectView:
 {
     public string Dependency[] { get; set; }
        ...
 }
我想将ProjectView类中的依赖项数组绑定到DataGridView

 class Editor
 {
     private readonly ProjectView _currentProjectView;

     ... //I skipped constructor and other methods  

     private void PopulateTabs()
     {
        BindingSource source = new BindingSource {DataSource = _currentProjectView.Dependencies, AllowNew = true};
        dataGridViewDependencies.DataSource = source;
     } 
  }
但当我这样绑定时,就会出现异常(AllowNew只能在IBindingList或具有默认公共构造函数的读写列表上设置为true),因为_currentProjectView.Dependencies是数组,它无法添加新项。 有一种解决方案是转换为列表,但并不方便,因为它只是复制并丢失了对原始数组的引用。这个问题有解决办法吗?如何将数组正确绑定到datagridview?
谢谢。

好的,假设您在内存中的某个地方有一个
依赖项
对象数组,您执行了如下操作:

arrayOfObjs.ToList();
BindingSource source = new BindingSource {DataSource = _currentProjectView.Dependencies, AllowNew = true};

dataGridViewDependencies.DataSource = _currentProjectView.Dependencies.ToList();
这不会改变他们指向的参考。因此,为了进一步说明这一点,它们来自的数组,如果它被持久化在内存中,它将看到所做的更改。现在,你会看到任何补充,不是吗?但这就是为什么要使用可变类型,比如
列表
,而不是数组

因此,我建议您这样做:

class ProjectView:
{
    public string List<Dependency> Dependencies { get; set; }
}
这将为您建立
依赖关系[]

编辑 请考虑以下结构:

class ProjectView:
{
    public Dependency[] Dependencies { get; set; }

    public List<Dependency> DependencyList { get { return this.Dependencies.ToList(); } }
}
编辑完成后:

_currentProjectView.Dependencies = _currentProjectView.DependencyList.ToArray();

我认为如果不使用集合,就无法将数组绑定到
DataGridView
。所以你必须使用这样的东西:

arrayOfObjs.ToList();
BindingSource source = new BindingSource {DataSource = _currentProjectView.Dependencies, AllowNew = true};

dataGridViewDependencies.DataSource = _currentProjectView.Dependencies.ToList();
发件人:

DataGridView类支持标准的Windows窗体数据绑定模型。这意味着数据源可以是实现以下接口之一的任何类型:

  • IList
    接口,包括一维数组

  • IListSource
    接口,例如
    DataTable
    DataSet

  • IBindingList
    接口,例如
    BindingList

  • IBindingListView
    接口,例如
    BindingSource


对于我来说,在填充Datagrid时,我总是使用DataTable或List对象,我永远不会使用数组。为什么您要确切地使用数组?但我不想更改ProjectView类,我不想更改ProjectView类,因为我使用的是PropertyGrid和Dependency属性view不适合。@AndrewOrlov,您可以尝试的一件事是在
ProjectView
类上将其作为
IList
公开。我相信
PropertyGrid
将使用同一个设计器进行响应,因为它的实际值是一维数组。它不起作用。属性网格已停止显示依赖属性。@AndrewOrlov,好的,我认为您有两个选择。第一个是在
ProjectView
中添加一个新属性,该属性是一个
get
属性,实际上只返回
Dependencies.ToList()
——我喜欢这个属性,因为它也维护了您需要的数组。或者,您可以在设置
DataGridView
DataSource
时构建列表。在构建DataSource期间,如何帮助我构建列表?我所能做的就是编辑依赖项,但如果我要添加新的依赖项,它将不会保存。