Sorted list not sorted when binding

931 views Asked by At

I have a sorted list. When I bind it to a listbox, it does not shows the item in an ordered manner.

territoryListBox.BeginUpdate();
this.Text = ((INamedEntity)_currentList[0]).Name;
territoryListBox.DataSource = _currentList;
territoryListBox.DisplayMember = "Name";
territoryListBox.Sorted = true;
territoryListBox.EndUpdate();

The first item in the list is, say, A. The this.Text shows "A", which is the first item in the list. But the listbox shows:

B
C
A

_currentList is a IList<>

2

There are 2 answers

1
Marc Gravell On

Are you swallowing an exception? When I try this I get (when setting Sorted) an ArgumentException:

Items collection cannot be modified when the DataSource property is set.

IMO, sort the list first - and bind to that; however, a quick test shows that setting Sorted before setting the DataSource works too - i.e.

territoryListBox.Sorted = true;
territoryListBox.DataSource = yourListOfData;
territoryListBox.DisplayMember = "Name";
1
JP Alioto On

Just for fun, try ListBox.Sort. Obviously, that should not be necessary, but something's going haywire.