Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

Displaying Output Based on Tree Item Selection

Generally, you won't display just a tree view of the XML data. It's possible to work with the view in a number of ways. This example uses the Tag property of leaf nodes to store a data value. You could also create code that re-parses the XML and checks for specific attributes, values, or elements based on the user selection. For that matter, you don't have to base the selection on the XML at all—you can create a calculated output or relate the information to the database. No matter what you decide to do, you need to handle the AfterSelect() event, as shown in Listing 4, to provide additional output.

Listing 4 Displaying Output Based on a User Selection

private void tvNodes_AfterSelect(object sender,
                 System.Windows.Forms.TreeViewEventArgs e)
  StringBuilder Output; // Contains the output for node.

  // Initialize the StringBuilder.
  Output = new StringBuilder();

  // Get the number of child nodes.
  Output.Append(" contains ");
  Output.Append(" children.");

  // Get the value of the element when available.
  if (e.Node.Tag != null)
   Output.Append("\r\nThe quantity of this item is: ");

  // Display the result on screen.
  txtContent.Text = Output.ToString();

The key element in this code is that the TreeView passes the node to the event handler as part of the TreeViewEventArgs variable e. The code uses this node to determine the number of children contained in the element, and it displays the value of the Tag property when there's a value to display. Figure 1 shows typical output from this application.

Figure 1Figure 1 Displaying a tree view with associated data.

As Figure 1 shows, the code nicely parses the XML data and displays it in an easy-to-understand format. The user can click the various entries, determine how many children the element has as a minimum, and optionally learn the value for leaf nodes. Notice that Pears is the only node displayed with the special leaf-node icon because it doesn't have any children of any type (not even a value).

  • + Share This
  • 🔖 Save To Your Account