I have a databound ListBox that is behaving strangely. The ListBox’s SelectionMode property is set to MultiExtended, and on a button click, I need to copy the items to another control, in this case, a TreeView. However, for some reason, every iterator I’ve tried only loops once. I’ve attempted both SelectedItems and SelectedIndices. Code excerpt:
var movedItems = new List<ListBoxUnderlyingObject>();
foreach (var selectedItem in listBox.SelectedItems)
{
var castItem = selectedItem as ListBoxUnderlyingObject;
var newNode = new TreeNode(castItem.SomeString);
newNode.Name = castItem.AnotherString;
newNode.Tag = castItem;
newNode.ForeColor = Color.RoyalBlue;
//parentNode was set earlier
parentNode.Nodes.Add(newNode);
movedItems.Add(selectedItem);
}
//use movedItems to remove items from listBox's underlying databound object and rebind
No matter how many items are selected, the loop only executes once. Same with SelectedIndices. If I attempt it with a numbered iterator, it fails with an “index out of bounds of array” error.
for(var i = 0;i < listBox.SelectedItems.Count;i++)
{
var castItem = listBox.SelectedItems[i] as ListBoxUnderlyingObject;
//etc., the previous line bombs on the second iteration
}
If I throw a Debug.WriteLine(listBox.SelectedItems.Count) either before or during the loop, it always reflects the correct count. I know this is probably something stupid, but I’m stumped. Help!
Follow Up
I’ve created a separate winforms project that emulates the behavior almost exactly, and SelectedItems works. I am completely baffled. Now, I’m going to try and add a new form in the original project and see if I can recreate the behavior there.
Well, it turns out I did withhold some critical information. The listbox has drag-drop behavior enabled, and part of this is a handler for the MouseDown event. The handler has this code in it:
If I comment this handler out,
SelectedItemsbehaves correctly. Now I have to figure out how to do the drag-drop stuff correctly, but that’s a different question.