6.2 Link Data to a Control


Problem

You need to link an object to a specific control (perhaps to store some arbitrary information that relates to a given display item).

Solution

Store a reference to the object in the Tag property of the control.

Discussion

Every class that derives from System.Windows.Forms.Control provides a Tag property that you can use to store a reference to any type of object. The Tag property isn't used by the control or the Microsoft .NET Framework. Instead, it's reserved as a convenient storage place for application-specific information. In addition, some other non- Control -derived classes provide a Tag property. Examples include the ListViewItem and TreeNode classes (which represent items in a ListView or a TreeView control). One class that does not provide a Tag property is MenuItem .

The Tag property is defined as a generic Object type, which means that you can use it to store any value type or reference type, from a simple number or string to a custom object you have defined. When retrieving data from the Tag property, you'll need to cast the object to its original type.

The following example adds a list of files to a list view. The corresponding FileInfo object for each file is stored in the Tag property. When a user double- clicks one of the list items, the code retrieves the FileInfo object from the Tag property and displays the file size in a MessageBox (see Figure 6.2).

 using System; using System.Windows.Forms; using System.IO; public class TagPropertyExample : System.Windows.Forms.Form (     // (Designer code omitted.)     private void TagPropertyExample_Load(object sender, System.EventArgs e) {              // Get all the files in the directory.         DirectoryInfo directory = new DirectoryInfo("C:\");         FileInfo[] files = directory.GetFiles();         // Display all the files in the ListView.         foreach (FileInfo file in files) {                      ListViewItem item = listView.Items.Add(file.Name);             item.ImageIndex = 0;             item.Tag = file;         }     }     private void listView_ItemActivate(object sender, System.EventArgs e) {              // Get the file's size from the linked FileInfo.         ListViewItem item = ((ListView)sender).SelectedItems[0];         FileInfo file = (FileInfo)item.Tag;         string info = file.FullName + " is " + file.Length + " bytes.";         // Display the file's size.         MessageBox.Show(info, "File Information");     } } 

Figure 6.2: Storing data in the Tag property.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net