Reputation: 235
I have interface IDoc and an abstract class that implements it named Doc. I then have a class named BookDoc that inherits from Doc and another class JournalDoc that also inherits from Doc.
Now what I would like to do is bind either a BindingList<BookDoc>
or BindingList<JournalDoc>
to a custom DataGridView. I then want to be able to access an Errors property the they both inherit from the Doc class.
semi working Example:
var dataSource = this.DataSource as BindingSource;
BindingList<BookDoc> tempBookDocs = dataSource.DataSource as BindingList<BookDoc>;
var Docs = new List<IDoc>();
foreach (var tempDoc in tempBookDocs)
{
Docs.Add(tempDoc);
}
The above example works and i get a list of Docs that is populated and i can access the Errors property but still have to hard code the type of list that was originally bound.
What i would like to do is something like this though I'm not sure it is possible.
var dataSource = this.DataSource as BindingSource;
BindingList<Doc> Docs = dataSource.DataSource as BindingList<Doc>;
This gives me a null Docs list though.
Upvotes: 0
Views: 1853
Reputation: 23770
If you're using .NET 4.0, you can take advantage of covariance using IEnumarable<>
:
IEnumarable<Doc> tempBookDocs = dataSource.DataSource as IEnumarable<Doc>;
var Docs = new List<IDoc>();
foreach (var tempDoc in tempBookDocs)
{
Docs.Add(tempDoc);
}
If you're using .NET 3.5, you can use LINQ OfType
extension method:
IEnumarable<Doc> myDocs = ((IEnumarable)dataSource.DataSource).OfType<Doc>();
var Docs = new List<IDoc>();
foreach (var tempDoc in myDocs)
{
Docs.Add(tempDoc);
}
Upvotes: 2