How to Casting DataSource to List<T>?

c# datagridview datasource list<string
datagridview to list c#
convert list to dataset c#
vb net datagridview datasource list of objects
convert list to datatable c#
convert dynamic list to datatable c#
convert list to datatable in c# using linq
datarowcollection to list

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?

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();

if you bind items as below. Hide Copy Code. List<display> DisplayItems =//get items; gridDisplay.DataSource =DisplayItems; then you can get it  The BindingSource class uniformly handles different data sources. Ideally the List property should be set to a general IList. However, sometimes it may be necessary to cast this property to a more specific type. The following table shows the underlying list type, which depends on the type or value of the data source.

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));

Suppose i have a List<> List<Employee> emp = new List<Employee>(); Employee ob = new Employee(); ob.Address = "1"; ob.City = "2"; emp. If you have a DataSource there usually isnt a good reason to convert to a List, least of all a List(Of Object). Whatever it is bound to is already a typed collection of some sort. – Ňɏssa Pøngjǣrdenlarp Jun 17 '16 at 22:48

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

With some custom List-to-DataTable conversion logic, we get the best performance from the DataGridView by using the DataSource property.Convert. I have bound array as datasource for ListBox . Now i need to convert listbox.Items to string of array collection. foreach (string s1 in listBoxPart.Items) { clist.Add(s1); } here clist is string

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.

NET, Resolves)ataSource performs a simple cast to IEnumerable. If the class implementing IListSource supports a bindable list, we need to use the For simple data source collections like Array or ArrayList, just cast dataSource parameter  I'm Trying to cast bindingsource to datatable using these codes BindingSource bs = (BindingSource)gvSideMember.DataSource; DataTable tCxC = (DataTable)bs.DataSource; this shows me this exception unable to cast bindingsource to datatable then tried this one

It enumerates the data list ' s bound data source . 2 . Casting is the process of converting an object of one type to another ( as in the preceding example ) . EDIT : Also I just read here List<T> vs BindingList<T> Advantages/DisAdvantages from Ilia Jerebtsov : "When you set a BindingSource's DataSource to a List<>, it internally creates a BindingList to wrap your list". I think my sample just demonstrates that this is not true : my List<> doesn't seem to be internally wrapped into a BindingList<>.

Binding DataSource with Array; Binding DataSource with List; Binding We can use this method to convert an enum to an array and bind to a  If you bind your list using DataSource, you can convert back by with: List<Class> myClass = DataGridView.DataSource as List<Class>;

To create an object binding data source, select Object on the first page of the So if you have, for example, a casting error at runtime, you will not see this error. Retrieve(CustomerID) ' For each row, create an object in the list For Each dr As​  Why you are casting like that directly give sqldatasource1 to dt (here you need to convert datasource to datatable). Permalink Posted 20-Nov-12 1:07am

Comments
  • What exactly does the exception say?
  • For Line List<Object> products = ((List<Product>)Source.DataSource).Cast<object>(); Cannot implicitly type 'System.COllections.Generic.IEnumerable<object>' to 'System.COllections.Generic.List<object>. An explicit convertion exists (are you missing a cast?)
  • You need a .ToList() at the end, my bad!
  • DataSource doesn't implement IEnumerable, so you'll need to cast it to that first.
  • @Servy, Thanks, Updated.
  • Same problem. AsEnumerable is an extension method of IEnumerable, not object.
  • Removed the last way. I was wondering How Cast<> can work and AsEnumerable cannot, while both accept IEnumerable as input?
  • Neither can work, that's what I'm saying. You need to do ((IEnumerable)Source.DataSource).Cast<object>() or OfType. DataSource is of type object not IEnumerable<object>.
  • what exactly is the input parameter type of SaveAll<Product>? are you sure you need a List<object>?
  • The idea is that SaveAll<T>(List<object>) is generic, so I will calling this method for all persistent objects. Products, Vendors, Makers, etc.
  • then it would make more sense if the signature is SaveAll<T>(List<T> ..., or even better SaveAll<T>(IEnumerable<T> ....