Binding an ArrayList to ListBox with Sort property set

  • Thread starter Thread starter Jason
  • Start date Start date
J

Jason

Here is an odd issue. I am trying to shed some light on why this is causing
a problem.

I have an ArrayList. I am binding it to a ListBox control with has its Sort
property set to True. If the ArrayList only has one element in it everything
works ok. But as soon as I have more than one element, I get the following
exception when the control loads up: "Cannot modify the Items collection
when the DataSource property is set.".

Anybody know what is happening?

- Jason
 
Hi Jason,

Like it says, if you want to modify (sort) the items, then you need to add them manully. However, you could sort the ArrayList before binding it to the ListBox.
 
So the Sort property on the ListBox actually modifies the underlying
DataSource instead of just how it is viewed in the ListBox?

- Jason
 
Not really. If a ListBox has a DataSource it makes no attempt to sort and setting Sorted = true will therefore cause an exception. ListBox blindly displays whatever is inside the DataSource.

If there is no datasource, that means it has full control of the list and can sort as much as it wants.

It may have something to do with the fact that various IList sources can have different ways of sorting.


So the Sort property on the ListBox actually modifies the underlying
DataSource instead of just how it is viewed in the ListBox?

- Jason
 
Thanks for the info Morten. It must be what you said... the way IList is
being implemented. I know this because I know I am not messing with the
items after being bound and when I upset the sorting property on the listbox
the exception goes away.

- Jason

Morten Wennevik said:
Not really. If a ListBox has a DataSource it makes no attempt to sort and
setting Sorted = true will therefore cause an exception. ListBox blindly
displays whatever is inside the DataSource.

If there is no datasource, that means it has full control of the list and
can sort as much as it wants.

It may have something to do with the fact that various IList sources can
have different ways of sorting.
 
Back
Top