0

I thought it is easy but it's not

I have windows form with bound listbox (with value member and display member)

I enabled multiselect for the listbox

so I need to get all and only the selected values of the selected items (remember it's bound so i need the selected values not text or selected text)

so i can insert these values in some other tables

i tried this but it doesn't work

 for (int x = 0; x <= listProjects.SelectedItems.Count; x++)
 {
     if(listProjects.GetSelected(x) == true)
     {
         string d = listProjects.SelectedValue.ToString();
         string s = listProjects.SelectedItems[x].ToString();

         //listProjects.DisplayMember[x].ToString();
         //listProjects.Items[x].ToString();
     }
  } 
VahidNaderi
  • 2,448
  • 1
  • 23
  • 35

2 Answers2

1

When you bind items to a ListBox, ListBox.Items would be of the type of items you bound to it so if supposedly your items are of type BoundItemType and Value is a property of BoundItemType you can do Something like this:

for (int x = 0; x <= listProjects.SelectedItems.Count; x++)
{
    BoundItemType boundItem = listProjects.SelectedItems[x] as BoundItemType;
    string selectedValue = boundItem.Value;
}
VahidNaderi
  • 2,448
  • 1
  • 23
  • 35
0

Suppose your DataSource has element type as ItemType, and the value member is ItemValue, we can cast each selected items (of object) to that type and get the value you want:

var values = listBox1.SelectedItems.OfType<ItemType>()
                                   .Select(item=>item.ItemValue).ToList();

You can always use Reflection without knowledge about the underlying item type beforehand, just to be sure the ValueMember is valid. However, I think this is just for reference, not recommended:

var values = listBox1.SelectedItems.OfType<object>()
                     .Select(item=> item.GetType()
                                        .GetProperty(listBox1.ValueMember)
                                        .GetValue(item, null)).ToList();
King King
  • 61,710
  • 16
  • 105
  • 130