Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

7.5 The ListView and TreeView Classes

The ListView Class

ListView is another control that displays lists of information. It represents data relationally as items and subitems. The data can be represented in a variety of formats that include a multi-column grid and large or small icons to represent item data. Also, images and check boxes can adorn the control.

Figure 7-11 illustrates the basic properties and methods used to lay out a Details view of the control—a format obviously tailored to displaying database tables. The first column contains text for an item—as well as a picture—the remaining columns contain subitems for the parent item.

Figure 7-11

Figure 7-11 ListView control

Let’s look at how this style of the ListView is constructed.

Creating a ListView Object

The ListView is created with a parameterless constructor:

ListView listView1 = new ListView();

Define Appearance of ListView Object

// Set the view to show details
listView1.View = View.Details;

The View property specifies one of five layouts for the control:

  • Details. An icon and item’s text are displayed in column one. Subitems are displayed in the remaining columns.
  • LargeIcon. A large icon is shown for each item with a label below the icon.
  • List. Each item is displayed as a small icon with a label to its right. The icons are arranged in columns across the control.
  • SmallIcon. Each item appears in a single column as a small icon with a label to its right.
  • *Tile. Each item appears as a full-size icon with the label and subitem details to the right of it. Only available for Windows XP and 2003.

After the Details view is selected, other properties that define the control’s appearance and behavior are set:

// Allow the user to rearrange columns
listView1.AllowColumnReorder = true;
// Select the entire row when selection is made
listView1.FullRowSelect = true;
// Display grid lines
listView1.GridLines = true;
// Sort the items in the list in ascending order
listView1.Sorting = SortOrder.Ascending;

These properties automatically sort the items, permit the user to drag columns around to rearrange their order, and cause a whole row to be highlighted when the user selects an item.

Set Column Headers

In a Details view, data is not displayed until at least one column is added to the control. Add columns using the Columns.Add method. Its simplest form is

ListView.Columns.Add(caption, width, textAlign)

Caption is the text to be displayed. Width specifies the column’s width in pixels. It is set to –1 to size automatically to the largest item in the column, or –2 to size to the width of the header.

// Create column headers for the items and subitems
  listView1.Columns.Add("Artist", -2, HorizontalAlignment.Left);
  listView1.Columns.Add("Born", -2, HorizontalAlignment.Left);
  listView1.Columns.Add("Died", -2, HorizontalAlignment.Left);
  listView1.Columns.Add("Country", -2, HorizontalAlignment.Left);

The Add method creates and adds a ColumnHeader type to the ListView’s Columns collection. The method also has an overload that adds a ColumnHeader object directly:

ColumnHeader cHeader:
cHeader.Text = "Artist";
cHeader.Width = -2;
cHeader.TextAlign = HorizontalAlignment.Left;
ListView.Columns.Add(ColumnHeader cHeader);

Create ListView Items

Several overloaded forms of the ListView constructor are available. They can be used to create a single item or a single item and its subitems. There are also options to specify the icon associated with the item and set the foreground and background colors.

Constructors:

public ListViewItem(string text);
public ListViewItem(string[] items );
public ListViewItem(string text,int imageIndex );
public ListViewItem(string[] items,int imageIndex );
public ListViewItem(string[] items,int imageIndex,
     Color foreColor,Color backColor,Font font);

The following code demonstrates how different overloads can be used to create the items and subitems shown earlier in Figure 7-8:

// Create item and three subitems
ListViewItem item1 = new ListViewItem("Manet",2);
item1.SubItems.Add("1832");
item1.SubItems.Add("1883");
item1.SubItems.Add("France");
// Create item and subitems using a constructor only
ListViewItem item2 = new ListViewItem
    (new string[] {"Monet","1840","1926","France"}, 3);
// Create item and subitems with blue background color
ListViewItem item3 = new ListViewItem
    (new string[] {"Cezanne","1839","1906","France"}, 1, 
    Color.Empty, Color.LightBlue, null);

To display the items, add them to the Items collection of the ListView control:

// Add the items to the ListView
  listView1.Items.AddRange(
   new ListViewItem[]{item1,item2,item3,item4,item5});

Specifying Icons

Two collections of images can be associated with a ListView control as ImageList properties: LargeImageList, which contains images used in the LargeIcon view; and SmallImageList, which contains images used in all other views. Think of these as zero-based arrays of images that are associated with a ListViewItem by the imageIndex parameter in the ListViewItem constructor. Even though they are referred to as icons, the images may be of any standard graphics format.

The following code creates two ImageList objects, adds images to them, and assigns them to the LargeImageList and SmallImageList properties:

// Create two ImageList objects
  ImageList imageListSmall = new ImageList();
  ImageList imageListLarge = new ImageList();
  imageListLarge.ImageSize = new Size(50,50); // Set image size
  // Initialize the ImageList objects 
  // Can use same images in both collections since they’re resized
  imageListSmall.Images.Add(Bitmap.FromFile("C:\\botti.gif"));
  imageListSmall.Images.Add(Bitmap.FromFile("C:\\cezanne.gif"));
  imageListLarge.Images.Add(Bitmap.FromFile("C:\\botti.gif"));
  imageListLarge.Images.Add(Bitmap.FromFile("C:\\cezanne.gif"));
  // Add other images here
  // Assign the ImageList objects to the ListView.
  listView1.LargeImageList = imageListLarge;
  listView1.SmallImageList = imageListSmall;
  ListViewItem lvItem1 = new ListViewItem("Cezanne",1);

An index of 1 selects the cezanne.gif images as the large and small icons. Specifying an index not in the ImageList results in the icon at index 0 being displayed. If neither ImageList is defined, no icon is displayed. Figure 7-12 shows the ListView from Figure 7-11 with its view set to View.LargeIcon:

listView1.View = View.LargeIcon;
Figure 7-12

Figure 7-12 LargeIcon view

Working with the ListView Control

Common tasks associated with the ListView control include iterating over the contents of the control, iterating over selected items only, detecting the item that has focus, and—when in Details view—sorting the items by any column. Following are some code segments to perform these tasks.

Iterating over All Items or Selected Items

You can use foreach to create nested loops that select an item and then iterate through the collection of subitems for the item in the outside loop:

foreach (ListViewItem lvi in listView1.Items)
{
  string row = "";
  foreach(ListViewItem.ListViewSubItem sub in lvi.SubItems)
  {
   row += " " + sub.Text;
  }
  MessageBox.Show(row); // List concatenated subitems
}

There are a couple of things to be aware of when working with these collections. First, the first subitem (index 0) element actually contains the text for the item—not a subitem. Second, the ordering of subitems is not affected by rearranging columns in the ListView control. This changes the appearance but does not affect the underlying ordering of subitems.

The same logic is used to list only selected items (MultiSelect = true permits multiple items to be selected). The only difference is that the iteration occurs over the ListView.SelectedItems collection:

foreach (ListViewItem lvisel in listView1.SelectedItems)
Detecting the Currently Selected Item

In addition to the basic control events such as Click and DoubleClick, the ListView control adds a SelectedIndexChanged event to indicate when focus is shifted from one item to another. The following code implements an event handler that uses the FocusedItem property to identify the current item:

// Set this in the constructor
listView1.SelectedIndexChanged +=
   new EventHandler(lv_IndexChanged);
// Handle SelectedIndexChanged Event
private void lv_IndexChanged(object sender, System.EventArgs e)
{
  string ItemText = listView1.FocusedItem.Text;
}

Note that this code can also be used with the Click events because they also use the EventHandler delegate. The MouseDown and MouseUp events can also be used to detect the current item. Here is a sample MouseDown event handler:

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
  ListViewItem selection = listView1.GetItemAt(e.X, e.Y);
  if (selection != null)
  {
   MessageBox.Show("Item Selected: "+selection.Text);
  }
}

The ListView.GetItemAt method returns an item at the coordinates where the mouse button is pressed. If the mouse is not over an item, null is returned.

Sorting Items on a ListView Control

Sorting items in a ListView control by column values is a surprisingly simple feature to implement. The secret to its simplicity is the ListViewItemSorter property that specifies the object to sort the items anytime the ListView.Sort method is called. Implementation requires three steps:

  1. Set up a delegate to connect a ColumnClick event with an event handler.
  2. Create an event handler method that sets the ListViewItemSorter property to an instance of the class that performs the sorting comparison.
  3. Create a class to compare column values. It must inherit the IComparer interface and implement the IComparer.Compare method.

The following code implements the logic: When a column is clicked, the event handler creates an instance of the ListViewItemComparer class by passing it the column that was clicked. This object is assigned to the ListViewItemSorter property, which causes sorting to occur. Sorting with the IComparer interface is discussed in Chapter 4, "Working with Objects in C#").

// Connect the ColumnClick event to its event handler
listView1.ColumnClick +=new ColumnClickEventHandler(ColumnClick);
// ColumnClick event handler
private void ColumnClick(object o, ColumnClickEventArgs e)
{
  // Setting this property immediately sorts the 
  // ListView using the ListViewItemComparer object
  this.listView1.ListViewItemSorter = 
    new ListViewItemComparer(e.Column);
}
// Class to implement the sorting of items by columns
class ListViewItemComparer : IComparer
{
  private int col;
  public ListViewItemComparer()
  {
   col = 0;  // Use as default column
  }
  public ListViewItemComparer(int column)
   {
   col = column;
  }
  // Implement IComparer.Compare method
  public int Compare(object x, object y)
  {
   string xText = ((ListViewItem)x).SubItems[col].Text;
   string yText = ((ListViewItem)y).SubItems[col].Text;
   return String.Compare(xText, yText);
  }
}

The TreeView Class

As the name implies, the TreeView control provides a tree-like view of hierarchical data as its user interface. Underneath, its programming model is based on the familiar tree structure consisting of parent nodes and child nodes. Each node is implemented as a TreeNode object that can in turn have its own Nodes collection. Figure 7-13 shows a TreeView control that is used in conjunction with a ListView to display enum members of a selected assembly. (We’ll look at the application that creates it shortly.)

Figure 7-13

Figure 7-13 Using TreeView control (left) and ListView (right) to list enum values

The TreeNode Class

Each item in a tree is represented by an instance of the TreeNode class. Data is associated with each node using the TreeNode’s Text, Tag, or ImageIndex properties. The Text property holds the node’s label that is displayed in the TreeView control. Tag is an object type, which means that any type of data can be associated with the node by assigning a custom class object to it. ImageIndex is an index to an ImageList associated with the containing TreeView control. It specifies the image to be displayed next to the node.

In addition to these basic properties, the TreeNode class provides numerous other members that are used to add and remove nodes, modify a node’s appearance, and navigate the collection of nodes in a node tree (see Table 7-3).

Table 7-3 Selected Members of the TreeNode Class

Use

Member

Description

Appearance

BackColor, ForeColor

Sets the background color and text color of the node.

Expand(), Collapse()

Expands the node to display child nodes or collapses the tree so no child nodes are shown.

Navigation

FirstNode, LastNode,

NextNode, PrevNode

Returns the first or last node in the collection.

Returns the next or previous node (sibling) relative to the current node.

Index

The index of the current node in the collection.

Parent

Returns the current node’s parent.

Node Manipulation

Nodes.Add(),

Nodes.Remove(),

Nodes.Insert(),

Nodes.Clear()

Adds or removes a node to a Nodes collection. Insert adds a node at an indexed location, and Clear removes all tree nodes from the collection.

Clone()

Copies a tree node and entire subtree.

Let’s look at how TreeView and TreeNode members are used to perform fundamental TreeView operations.

Adding and Removing Nodes

The following code creates the tree in Figure 7-14 using a combination of Add, Insert, and Clone methods. The methods are performed on a preexisting treeView1 control.

TreeNode tNode;
// Add parent node to treeView1 control
tNode = treeView1.Nodes.Add("A");
// Add child node: two overloads available
tNode.Nodes.Add(new TreeNode("C"));
tNode.Nodes.Add("D"));
// Insert node after C
tNode.Nodes.Insert(1,new TreeNode("E"));
// Add parent node to treeView1 control 
tNode = treeView1.Nodes.Add("B");
Figure 7-14

Figure 7-14 TreeView node representation

At this point, we still need to add a copy of node A and its subtree to the parent node B. This is done by cloning the A subtree and adding it to node B. Node A is referenced as treeView1.Nodes[0] because it is the first node in the control’s collection. Note that the Add method appends nodes to a collection, and they can be referenced by their zero-based position within the collection:

// Clone first parent node and add to node B
TreeNode clNode = (TreeNode) treeView1.Nodes[0].Clone();
tNode.Nodes.Add(clNode);
// Add and remove node for demonstration purposes
tNode.Nodes.Add("G");
tNode.Nodes.Remove(tNode.LastNode);
Iterating Through the Nodes in a TreeView

As with any collection, the foreach statement provides the easiest way to loop through the collection’s members. The following statements display all the top-level nodes in a control:

foreach (TreeNode tn in treeView1.Nodes)
{
  MessageBox.Show(tn.Text);
  // If (tn.IsVisible) true if node is visible
  // If (tn.IsSelected) true if node is currently selected
}

An alternate approach is to move through the collection using the TreeNode.NextNode property:

tNode = treeView1.Nodes[0];
while (tNode != null) {
  MessageBox.Show(tNode.Text);
  tNode = tNode.NextNode;
}
Detecting a Selected Node

When a node is selected, the TreeView control fires an AfterSelect event that passes a TreeViewEventArgs parameter to the event handling code. This parameter identifies the action causing the selection and the node selected. The TreeView example that follows illustrates how to handle this event.

You can also handle the MouseDown event and detect the node using the GetNodeAt method that returns the node—if any—at the current mouse coordinates.

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
  TreeNode tn = treeView1.GetNodeAt(e.X, e.Y);
  // You might want to remove the node: tn.Remove()
}

A TreeView Example That Uses Reflection

This example demonstrates how to create a simple object browser (refer to Figure 7-13) that uses a TreeView to display enumeration types for a specified assembly. When a node on the tree is clicked, the members for the selected enumeration are displayed in a ListView control.

Information about an assembly is stored in its metadata, and .NET provides classes in the System.Reflection namespace for exposing this metadata. The code in Listing 7-4 iterates across the types in an assembly to build the TreeView. The parent nodes consist of unique namespace names, and the child nodes are the types contained in the namespaces. To include only enum types, a check is made to ensure that the type inherits from System.Enum.

Listing 7-4 Using a TreeView and Reflection to List Enums in an Assembly

using System.Reflection;
// 
private void GetEnums()
{
  TreeNode tNode=null;
  Assembly refAssembly ;
  Hashtable ht= new Hashtable(); // Keep track of namespaces
  string assem = AssemName.Text; // Textbox with assembly name
  tvEnum.Nodes.Clear();      // Remove all nodes from tree
  // Load assembly to be probed
  refAssembly = Assembly.Load(assem);
  foreach (Type t in refAssembly.GetTypes())
  {
   // Get only types that inherit from System.Enum
   if(t.BaseType!=null && t.BaseType.FullName=="System.Enum")
   {
     string myEnum = t.FullName;
     string nSpace = 
          myEnum.Substring(0,myEnum.LastIndexOf("."));
     myEnum= myEnum.Substring(myEnum.LastIndexOf(".")+1) ;
     // Determine if namespace in hashtable
     if( ht.Contains(nSpace))
     {
      // Find parent node representing this namespace
      foreach (TreeNode tp in tvEnum.Nodes)
      {
       if(tp.Text == myEnum) { tNode=tp; break;}
      }
     }
     else
     {
      // Add parent node to display namespace
      tNode = tvEnum.Nodes.Add(nSpace);
      ht.Add(nSpace,nSpace);
     }
     // Add Child - name of enumeration
     TreeNode cNode = new TreeNode();
     cNode.Text= myEnum;
     cNode.Tag = t;   // Contains specific enumeration
     tNode.Nodes.Add(cNode);
   }
  }
}

Notice how reflection is used. The static Assembly.Load method is used to create an Assembly type. The Assembly.GetTypes is then used to return a Type array containing all types in the designated assembly.

refAssembly = Assembly.Load(assem);
foreach (Type t in refAssembly.GetTypes())

The Type.FullName property returns the name of the type, which includes the namespace. This is used to extract the enum name and the namespace name. The Type is stored in the Tag field of the child nodes and is used later to retrieve the members of the enum.

After the TreeView is built, the final task is to display the field members of an enumeration when its node is clicked. This requires registering an event handler to be notified when an AfterSelect event occurs:

tvEnum.AfterSelect += new 
  TreeViewEventHandler(tvEnum_AfterSelect);

The event handler identifies the selected node from the TreeViewEventArgs.Node property. It casts the node’s Tag field to a Type class (an enumerator in this case) and uses the GetMembers method to retrieve the type’s members as MemberInfo types. The name of each field member—exposed by the MemberInfo.Name property—is displayed in the ListView:

// ListView lView;
// lView.View = View.List; 
private void tvEnum_AfterSelect(Object sender, 
                TreeViewEventArgs e)
{
  TreeNode tn = e.Node;  // Node selected
  ListViewItem lvItem;  
  if(tn.Parent !=null)  // Exclude parent nodes
  {
   lView.Items.Clear(); // Clear ListView before adding items
   Type cNode = (Type) tn.Tag;
   // Use Reflection to iterate members in a Type
   foreach (MemberInfo mi in cNode.GetMembers())
   {
     if(mi.MemberType==MemberTypes.Field &&
              mi.Name != "value__" ) // skip this
     {
      lView.Items.Add(mi.Name);
     }
   }
  }
}
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020