从列表视图中选择项目并投射到我的自定义对象 [英] select item from listview and cast to my custom object
问题描述
我正在尝试从列表视图中选择对象,并将其转换为这样的自定义对象
I'm trying to select object from listview and cast to my custom object like this
MyObject foo = (MyObject)MyListView.SelectedItems[0];
但这是我的编译错误
错误4无法将类型'System.Windows.Forms.ListViewItem'转换为
'MyObject'
Error 4 Cannot convert type 'System.Windows.Forms.ListViewItem' to 'MyObject'
推荐答案
默认 ListView
是不可数据绑定的(即,您不能将某些对象分配为列表视图的数据源)。它包含 ListViewItem
对象,这些对象不能转换为您的数据类型。这就是为什么出现此错误的原因。
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.
如果要从 ListViewItem
获取自定义对象,则需要构造从 ListViewItem
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);
或者您可以将自定义对象存储在 Tag
中 ListViewItem
的属性并将其取回:
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考虑使用 DataGridView
支持绑定
BTW consider to use DataGridView
which supports binding.
这篇关于从列表视图中选择项目并投射到我的自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!