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.
See the example listed on MSDN. Instead of using selected item / items / index / indices, they recommend you iterate over each list item and use the GetSelected Method to determine whether the given index has been selected.
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:
private void listBox_MouseDown(object sender, MouseEventArgs e)
{
if (listBox.Items.Count = 0) return;
listBox.DoDragDrop(listBox.SelectedItem, DragDropEffects.Move);
}
If I comment this handler out, SelectedItems
behaves correctly. Now I have to figure out how to do the drag-drop stuff correctly, but that's a different question.
I experienced the same problem and It took me to the verge of going crazy. I don't have an explanation but I have a workaround: set the DisplayMember property of the ListBox. It "should" work with the ToString() method but for some reason it does not work, so I implemented a property that returns the value of ToString and mapped the DisplayMember to that property. I wish you luck.
精彩评论