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
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
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.
The Tag property from Msdn
An Object that contains data about the control. The default is null.
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.
Example code:
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);
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
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.
Create new listviewitem object. use Tag property.
Quickest way around this is to keep a list of your object on the side:
List<MyObject> list = ... ; // my list
Generate a dictionary from the list with a string as the ID, or you can use the index to retrieve from the original list:
Dictionary<int,string> listBinder = new Dictionary<int,string>(
list.Select(i => new KeyValuePair<int,string>(i.ID, i.Name))
);
Bind or codebehind attaching the listview to the dictionary, then use the selected item to retrieve your object from your private list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With