select item from listview and cast to my custom object

后端 未结 3 1666
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 20:13

I\'m trying to select object from listview and cast to my custom object like this

MyObject foo = (MyObject)MyListView.SelectedItems[0];

but thi

3条回答
  •  轮回少年
    2021-01-22 21:05

    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.

提交回复
热议问题