How can I retrieve multiple selected listbox items and cast them to objects?
Similar question: .NET 3.5 Listbox Selected Values (Winforms)
I have a listbox populated using data binding to a collection of objects:
lstbDataFields.DisplayMember = "HumanReadable";
lstbDataFields.ValueMember = "DatabaseName";
lstbDataFields.DataSource = new BindingSource(Obj开发者_运维知识库ectCollection).OrderBy(d => d.HumanReadable), null);
I am looking for a way to pass the selected collection of these objects to a method. Something like this:
ProcessSelection((IEnumerable<ClassDataField>)lstbDataFields.SelectedItems);
This results in an InvalidCastException
.
What's the best way to get a proper collection of my object type from this listbox?
ProcessSelection(lstbDataFields.SelectedItems.Cast<ClassDataField>())
should do what you want (add a System.Linq using statement)
精彩评论