I\'m trying to select object from listview and cast to my custom object like this
MyObject foo = (MyObject)MyListView.SelectedItems[0];
but thi
Default ListView
is not data-bindable (i.e. you can't assign some objects as data source of list view). It contains ListViewItem
objects, which cannot be casted to your data type. That's why you getting this error.
If you want to get your custom object from ListViewItem
then you need to construct it manually from ListViewItem
:
ListViewItem item = (MyObject)MyListView.SelectedItems[0];
MyObject foo = new MyObject();
foo.FirstName = item.Text;
foo.LastName = item.SubItems[1].Text;
foo.Age = Int32.Parse(item.SubItems[2].Text);
OR you can store custom object in Tag
property of ListViewItem
and get it back:
ListViewItem item = (MyObject)MyListView.SelectedItems[0];
MyObject foo = (MyObject)item.Tag;
BTW consider to use DataGridView
which supports binding.