listbox multiselect madness

  • Thread starter Thread starter chauncy
  • Start date Start date
C

chauncy

Hey all,

On a windows form, I have a databound listbox with multiselect. All I want
to is spin through the selected items and find the value for each.

I've been everywhere and still haven't found a way to do this.
Please don't show me thee xample with listitem. There are no listitems
in windows forms.

Little help...
 
If you read .NET document/Visual Studio help on
System.Windows.Forms.ListBox, you can find ListBox.SelectedItems or
ListBox.SelectedIndices is what you want. Here is the excerpt from .NET
document:

For a multiple-selection ListBox, this property returns a collection
containing all items that are selected in the ListBox. For a
single-selection ListBox, this property returns a collection containing a
single element containing the only selected item in the ListBox. For more
information on how to manipulate the items of the collection, see
ListBox.SelectedObjectCollection.

The ListBox class provides a number of ways to reference selected items.
Instead of using the SelectedItems property to obtain the currently selected
item in a single-selection ListBox, you can use the SelectedItem property.
If you want to obtain the index position of an item that is currently
selected in the ListBox, instead of the item itself, use the SelectedIndex
property. In addition, you can use the SelectedIndices property if you want
to obtain the index positions of all selected items in a multiple-selection
ListBox.
 
1)
for (int i = 0; i < listBox.SelectedIndices.Count; i++)
{
object selectedItem1 = listBox.Items[this.listBox1.SelectedIndices];
// or
object selectedItem2 = listBox.SelectedItems;
}

2)
foreach (int selectedIndex in listBox.SelectedIndices)
{
}

3)
foreach (object selectedItem in this.listBox1.SelectedItems)
{
}

4)
for (int i = 0; i < this.listBox1.SelectedItems.Count; i++)
{
object selectedItem = listBox1.SelectedItems;
}


As you can see there are several ways to get the selected items from a
listbox and depending on what you want to do with the items you can choose.

Gabriel Lozano-Morán
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top