Cristhian Boujon
Cristhian Boujon

Reputation: 4190

How to Casting DataSource to List<T>?

I have the following method that load products on a DataGridView

private void LoadProducts(List<Product> products)
{
    Source.DataSource = products;  // Source is BindingSource
    ProductsDataGrid.DataSource = Source;
}

And now I'm trying to give me back to save them as shows below.

private void SaveAll()
{
   Repository repository = Repository.Instance;
   List<object> products = (List<object>)Source.DataSource; 
   Console.WriteLine("Este es el número {0}", products.Count);
   repository.SaveAll<Product>(products);
   notificacionLbl.Visible = false;
}

But I get an InvalidCastException on this line:

List<object> products = (List<object>)Source.DataSource;

So how can I cast the DataSource to an List?

Upvotes: 20

Views: 45915

Answers (4)

Cristhian Boujon
Cristhian Boujon

Reputation: 4190

Convining the answers This is my solution:

private void SaveAll()
{
    Repository repository = Repository.Instance;
    List<Product> products = (List<Product>)Source.DataSource;
    IEnumerable<object> objects = products.Cast<object>();
    repository.SaveAll<Product>(objects.ToList<object>());
    notificacionLbl.Visible = false;
}

I accept constructive criticisms.

Upvotes: 0

Tilak
Tilak

Reputation: 30688

So how can I cast the DataSource to an List?

You have plenty of options

var products = (List<Product>)Source.DataSource; // products if of type List<Product>

or

 List<Object> products = ((IEnumerable)Source.DataSource).Cast<object>().ToList();

or

List<Object>  products = ((IEnumerable)Source.DataSource).OfType<object>().ToList();

or

List<Object> products = new List<Object>();
((IEnumerable)Source.DataSource).AsEnumerable().ToList().ForEach( x => products.Add( (object)x));

Upvotes: 6

Dave Bish
Dave Bish

Reputation: 19646

You can't cast covariantly directly to List;

Either:

List<Product> products = (List<Product>)Source.DataSource;

or:

List<Object> products = ((List<Product>)Source.DataSource).Cast<object>().ToList();

Upvotes: 25

CubeSchrauber
CubeSchrauber

Reputation: 1199

Your List ist of type List<Product> which is different from List<object>. Try to cast to List<Product>

Upvotes: 3

Related Questions