Quicker
Quicker

Reputation: 37

Retrieving selected values from ListBox with multiselect

I have one WPF ListBox loaded using LINQ:

lbxCalculosSec.ItemsSource = from p in database.CALCULOS
                             orderby p.NOMBRECALCULO
                             select new { ID = p.IDCALCULO, NOMBRE = p.NOMBRECALCULO + " - " + p.DESCRIPCIONCALCULO };

lbxCalculosSec.DisplayMemberPath = "NOMBRE";
lbxCalculosSec.SelectedValuePath = "ID";

The listbox has multiselect = true. The problem is when I try to retrieve all the SelectedValue's (ID's) from SelectedItems List.

When I inspect one SelectedItem at runtime, the object type is "<>f__AnonymousType0`2"

I tried using this:

ItemPropertyInfo ID  = null;

lbxCalculosSec.SelectedItem.GetType().GetProperty("ID").GetValue(ID as ItemPropertyInfo, null)

But it didn't work.

I need a solution to access ListBox Selected Values (ID fields).

Thank you very much in advance.

Kind Regards.

Upvotes: 3

Views: 1964

Answers (2)

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

GetValue is expecting source for value so you should use SelectedItem there, not some random value and definitely not null.

Upvotes: 0

Elisha
Elisha

Reputation: 23770

GetValue expects the instance on which the property is defined, in this case it's the SelectedItem:

var item = lbxCalculosSec.SelectedItem;
ItemPropertyInfo ID  = (ItemPropertyInfo)item.GetType()
                                             .GetProperty("ID")
                                             .GetValue(item, null);

Edit
If ID is of some other type, like int, the code should be:

var item = lbxCalculosSec.SelectedItem;
int ID  = (int)item.GetType()
                   .GetProperty("ID")
                   .GetValue(item, null);

Upvotes: 3

Related Questions