how to iterate through a listbox selected items and get ValueMember and Display Member

10k Views Asked by At

Hello I am trying to iterate through the selected items of a listbox in winforms like this:

foreach (ListBox item in sknBox.SelectedItems)            
{              
    Console.WriteLine(item.ValueMember);
    Console.WriteLine(item.DisplayMember);     
}

But I get the following error:

Unable to cast object of type 'System.Data.DataRowView' to type 'System.Windows.Forms.ListBox'.

Is there a way to fix this? or another straight forward solution?

5

There are 5 best solutions below

6
sujith karivelil On BEST ANSWER

From the error message it is clear that the .SelectedItems is a collection of System.Data.DataRowView, so you can access the required values through Row with indexers as like the following:

foreach (var item in sknBox.SelectedItems)            
{              
    Console.WriteLine(((DataRowView)item).Row["Value-member-name-here"].ToString());
    Console.WriteLine(((DataRowView)item).Row["Display-member-name-here"].ToString());     
}
0
woelfchen42 On

I think the type of item should be the type of the Element of sknBox.SelectedItems. I afraid that your sknBox will not contain other ListBoxes. Or just use var for the type.

0
Kempeth On

ListBox.SelectedItems is a collection of Object not ListBox.

The easiest approach would be to hardcode it like:

foreach (Object item in sknBox.SelectedItems)            
{              
    Console.WriteLine((item as MyObject).Value); // or whatever it happens to be
    Console.WriteLine((item as MyObject).Label);     
}

If you for some reason need to be flexible I guess you could determine the type of the item and use reflection to call the getter on whatever property is assigned to ValueMember and DisplayMember.

1
Kevin Sijbers On

Before i begin: I'm not a 100% sure on the naming of the classes in winform (specifically ListBoxItem), so make sure you look these up if needed.

You have to cast the items to the correct type before you are able to use them the way you are

foreach (ListBoxItem item in sknBox.SelectedItems)            
{
    if(item is DataRowView) //Check if the item can be cast to your class
    {
        DataRowView drwItem = item as DataRowView;
        Console.WriteLine(drwItem.ValueMember);
        Console.WriteLine(drwItem.DisplayMember);    
    } 
}
0
Norbert Forgacs On

Based on un-lucky's answer the correct way to do it is:

foreach (DataRowView item in sknBox.SelectedItems)
{
    Console.WriteLine(item.Row["ID"].ToString());
    Console.WriteLine(item.Row["Description"].ToString());
}