如何插入对象类型中的ListView? [英] How to Insert Object Type in ListView?

查看:71
本文介绍了如何插入对象类型中的ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要保持我的ListView两个ID和对象类型。我试图做到这一点:

I want to maintain both ID and Object Type in my ListView. I'm trying to do this:

lstView.Items.Insert(MyObject);
// can't do this, because it takes only Int and String

在我情况下,ID为int,所以这部分是确定。但是如何将一个对象类型,并在Item_Selection更改事件找回?

In my case, the ID is int, so that part is ok. But how to insert an object type and retrieve it in the Item_Selection changed event?

推荐答案

A 的ListView 不能添加或直接插入对象如的ListBox 组合框,而是需要创建一个 ListViewItem的并设置其标签属性。

A ListView cannot add or insert an object directly like a ListBox or ComboBox, but instead you need to create a ListViewItem and set its Tag property.

从MSDN Tag属性。

The Tag property from Msdn

这包含了控制数据的对象。默认为空。

An Object that contains data about the control. The default is null.

从Object类派生的任何类型都可以分配给该
属性。如果标签属性是通过Windows窗体
设计师设置,只有文字可以分配。为标签
属性的一个常见用途是存储是密切与控制相关的数据。
为例,如果你有一个显示约
客户信息的控制,你可能会存储在包含客户的订单
历史,该控件的标签属性,以便可以将数据访问$一个DataSet ; b $ b迅速

Any type derived from the Object class can be assigned to this property. If the Tag property is set through the Windows Forms designer, only text can be assigned. A common use for the Tag property is to store data that is closely associated with the control. For example, if you have a control that displays information about a customer, you might store a DataSet that contains the customer's order history in that control's Tag property so the data can be accessed quickly.

示例代码:

MyObject myObj = new MyObject();

ListViewItem item = new ListViewItem();
item.Text = myObj.ToString(); // Or whatever display text you need
item.Tag = myObj;

// Setup other things like SubItems, Font, ...

listView.Items.Add(item);

当你需要得到你的对象从的ListView回,您可以施放标签属性。

When you need to get your object back from the ListView, you can cast the Tag property.

private void OnListViewItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) {
    MyObject myObj = (MyObject)e.Item.Tag;
    int id = myObj.Id;

    // Can access other MyObject Members
}



通常它更容易包装功能集成到一个辅助方法。

Usually its easier to wrap the functionality into a helper method.

public static void CreateListViewItem(ListView listView, MyObject obj) {
    ListViewItem item = new ListViewItem();
    item.Tag = obj;

    // Other requirements as needed

    listView.Items.Add(item);
}



你可以这样做:

And you can do:

CreateListViewItem(listView, obj);



A 的ListView 不支持数据源财产一样不少的控制,因此,如果您希望将数据绑定,您将需要实施一些更习惯。

A ListView doesn't support a DataSource property like a lot of controls, so if you wish to data bind you will need to implement something a bit more custom.

这篇关于如何插入对象类型中的ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆