Subscribe

RSS Feed (xml)

Link Data to a Control in C#

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.

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");
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail