This is code from one of my applications. I am showing you how to (1) declare your own class to save a variety of values, (2) how to save the class into the Tag property and (3) how to retrieve the class object or one of the values stored in the class object from the Tag property.
Sample Code - Declare a class to save information in a ListViewItem Tag property
A class named EquipmentClass that will hold information that I want to store in the ListView Tag property but not display in the ListView control.
class EquipmentClass
{
internal EquipmentClass(string WO_Alert, long Code, long Type) : base()
{
this.m_WO_Alert = WO_Alert;
this.m_Code = Code;
this.m_Type = Type;
}
internal string WO_Alert {
get { return m_WO_Alert; }
set { m_WO_Alert = value; }
}
internal long Code {
get { return m_Code; }
set { m_Code = value; }
}
internal long Type {
get { return m_Type; }
set { m_Type = value; }
}
private string m_WO_Alert;
private long m_Code;
private long m_Type;
}
Sample Code - Put EquipmentClass into ListViewItem Tag property
This code demonstrates how a ListViewItem is instantiated and populated with the SubItems and the Tag property. In my program, this code is in a While loop in which data is returned from the database into an SQLDataReader object named
rs.
string strAlert;
ListViewItem lstViewItem;
lstViewItem = new ListViewItem(rs("Description").ToString);
lstViewItem.SubItems.Add(rs("Model").ToString);
lstViewItem.SubItems.Add(rs("Serial").ToString);
lstViewItem.SubItems.Add(rs("Location").ToString);
lstViewItem.SubItems.Add(rs("Inventory_Number").ToString);
lstViewItem.SubItems.Add(rs("Desig").ToString);
lstViewItem.SubItems.Add(rs("Manufacturer").ToString);
if (rs.IsDBNull(rs.GetOrdinal("WO_Alert"))) {
strAlert = "N";
} else {
strAlert = Convert.ToString(rs("WO_Alert"));
}
lstViewItem.Tag = new EquipmentClass(strAlert, Convert.ToInt64(rs("Code")), Convert.ToInt64(rs("Type_Code")));
lstInventory.Items.Add(lstViewItem);
Sample code - Retrieving values from the TAG property
You can retrieve individual values from the EquipmentClass object within the Tag property or you could retrieve the entire object into a local variable of EquipmentClass type. Note that the Tag property is cast as the EquipmentClass class. This example retrieves only the Code property of the EquipmentClass for the ListViewItem that is at index
idx in the ListView control.
myVariableName = ((EquipmentClass)lstInventory.Items(idx).Tag).Code