views:

662

answers:

4

Hi There,

Is it possible to cast an IEnumerable list to a BindingList collection?

The IEnumerable list is a list of typed objects e.g:

IEnumerable<AccountInfo> accounts = bll.GetAccounts(u.UserName, u.Password);

And my PagingList just extends BindingList:

public class PagingList<T> 
{
    public BindingList<T> Collection { get; set; }
    public int Count { get; set; }

    public PagingList()
    {
        Collection = new BindingList<T>();
        Count = 0;
    }
}

I just wanted to pass my IEnumerable list to a method that renders out the list with my PagingControl:

 protected void RenderListingsRows(PagingList<AccountInfo> list)
   {
     foreach (var item in list)
     {
       //render stuff
     }
   }

But it seems i cannot cast between the two, can anyone point out what i'm missing?!

Many thanks

Ben

+1  A: 

BindingList<T> implements IEnumerable<T>, but not all IEnumerable<T> are binding lists (in fact, most aren't).

You should be able to create a new BindingList and add the items in the enumerable instance.

Lucero
+1  A: 

You pass PagingList into your RenderListingsRows, which does not implement IEnumerable.

In general, for PagingList to be an extension over BindingList it has to implement all interfaces that BindingList implements. But currently it does not implement any of them.

You should either inherit PagingList from BindingList, or implement all these interfaces, even if simply by calling methods of Collection object.

Or, you can just simply write for (var item in list.Collection)

Maxim Alexeyev
A: 

If your accounts collection implements IList<AccountInfo> you should be able to do this:

PagedList<AccountInfo> paged = new PagedList<AccountInfo>();
paged.Collection = new BindingList<AccountInfo>((IList<AccountInfo>)accounts);
Martin Brown
A: 

Send the binding list to the RenderListingsRows not the paging list. PagingList does not extend BindingList it uses composision instead. Hence the issue.

Example below.

 public class PagingList<T>
        {
            public BindingList<T> Collection { get; set; }
            public int Count { get; set; }

            public PagingList()
            {
                Collection = new BindingList<T>();
                Count = 0;
            }

        }

        public void CallRenderListingsRows()
        {
            var pagingList = new PagingList<PostcodeDetail>();

            RenderListingsRows(pagingList.Collection);
        }

        protected void RenderListingsRows(BindingList<PostcodeDetail> list)
        {
            foreach (var item in list)
            {
                //render stuff
            }
        }
CountZero