There are a Dependency class with some properties
class Dependency:
{
public string ArtifactId { get; set; }
public string GroupId { get; set; }
public string Version { get; set; }
public Dependency() {}
}
and ProjectView class:
class ProjectView:
{
public string Dependency[] { get; set; }
...
}
I want to bind array of Dependencies from ProjectView class to 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;
}
}
But when I’m binding like that, then exception occurs (AllowNew can only be set to true on an IBindingList or on a read-write list with a default public constructor.), because _currentProjectView.Dependencies is array, and it can’t be able to add new items.
There is solution is convert to list, but it is not convenient, because it’s just copy and lost reference to origin array. Is there solution of this problem? How to bind properly array to datagridview?
Thanks.
Okay, so let’s say you had an array of those
Dependencyobjects in memory somewhere, and you did something like this:That’s not going to change the reference they point to. So, to further that point, the array they came from, if it were persisted in memory, it would see the changes made. Now, will you see any additions, no? But that’s why you use a mutable type like a
Listinstead of an array.So, my recommendation is that you do this:
And dump the array. If the original list of
Dependencyis coming from an array, well then just issue theToListmethod on it and dump it. When you want to get an array back out of it (maybe you need to pass an array back), just do this:That will build
Dependency[]for you.EDIT
So consider the following structure:
Then in the form:
And then when editing is finished: