1

consider the following structure

class A {}
class B : A {}
class C : A {}
class D : A {}
...

// in data source class
BindingList<B> d1;
BindingList<C> d2;
BindingList<D> d3;
...

// in datagridview class
void BindDataSource(BindingList<A> source);
void QueryDataSource() {
  BindingList<A> source = (BindingList<A>)dgv.DataSource;
  A a = source.First(...);
}

I'd like to bind d1 and d2 ... to a DataGridView through BindDataSource sot that any change to d1 and d2 will automatically be reflected in DataGridView. From this post I learned that the above code is not valid. But none of the solutions in that post apply to my situation. I tried to change BindDataSource to the following

void BindingDataSource<T>(BindingList<T> source) where T:A;

but now QueryDataSource does not compile as I cannot cast the DataSource. Is there any way to solve the whole thing ?

Community
  • 1
  • 1
Monster Hunter
  • 846
  • 1
  • 12
  • 24

1 Answers1

1

A few options.

Option 1: Let d1...d3 be BindingList<A> instances, but only insert B, C, D into them.

Option 2: Have one collection, and query out/filter by B, C and D when needed.

Option 3: Do something like this.

BindDataSource(
    new BindingList<A>(d1.ToList<A>())
)

Option 4: Use a generic method.

void BindDataSource<T>(BindingList<T> list) where T : A { }
Colin
  • 4,025
  • 21
  • 40