Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 115 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
115
Dung lượng
1,91 MB
Nội dung
Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 310 310 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS treated as transparent for all images (this color is also known as the key color). The images will be resized accordingly by the control as they’re displayed. Figure 9.5 The Images Collection Editor dialog box The other method of adding images to an ImageList control is to call the Add method of the Images collection, which contains all the images stored in the control. To add an image at runtime, you must first create an Image object with the image (or icon) you want to add to the control and then call the Add method as follows: ImageList1.Images.Add(image) where image is an Image object with the desired image. You will usually call this method as follows: ImageList1.Images.Add(Image.FromFile(path)) where path is the full path of the file with the image. The Images collection of the ImageList control is a collection of Image objects, not the files in which the pictures are stored. This means that the image files need not reside on the computer on which the application will be executed, as long as they have been added to the collection at design time. The TreeView Control Let’s start our discussion with a few simple properties that you can set at design time. To experi- ment with the properties discussed in this section, open the TreeViewDemo project. The project’s main form is shown in Figure 9.6. After setting some properties (they are discussed next), run the project and click the Populate button to populate the control. After that, you can click the other buttons to see the effect of the various property settings on the control. Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 311 THE TREEVIEW CONTROL 311 Figure 9.6 The TreeViewDemo project demonstrates the basic properties and methods of the TreeView control. Here are the basic properties that determine the appearance of the control: ShowCheckBoxes If this property is True, a check box appears in front of each node. If the control displays check boxes, you can select multiple nodes; otherwise, you’re limited to a single selection. FullRowSelect This True/False value determines whether a node will be selected even if the user clicks outside the node’s caption. HideSelection This property determines whether the selected node will remain highlighted when the focus is moved to another control. By default, the selected node doesn’t remain highlighted when the control loses the focus. HotTracking This property is another True/False value that determines whether nodes are highlighted as the pointer hovers over them. When it’s True, the TreeView control behaves like a web document with the nodes acting as hyperlinks — they turn blue while the pointer hovers over them. Use the NodeMouseHover event to detect when the pointer hovers over a node. Indent This property specifies the indentation level in pixels. The same indentation applies to all levels of the tree — each level is indented by the same number of pixels with respect to its parent level. PathSeparator A node’s full name is made up of the names of its parent nodes, separated by a backslash. To use a different separator, set this property to the desired symbol. ShowLines The ShowLines property is a True/False value that determines whether the control’s nodes will be connected to its parent items with lines. These lines help users visualize the hierarchy of nodes, and it’s customary to display them. ShowPlusMinus The ShowPlusMinus property is a True/False value that determines whether the plus/minus button is shown next to the nodes that have children. The plus button is displayed when the node is collapsed, and it causes the node to expand when clicked. Like- wise, the minus sign is displayed when the node is expanded, and it causes the node to collapse Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 312 312 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS when clicked. Users can also expand the current node by pressing the left-arrow button and collapse it with the right-arrow button. ShowRootLines This is another True/False property that determines whether there will be lines between each node and root of the tree view. Experiment with the ShowLines and ShowRootLines properties to find out how they affect the appearance of the control. Sorted This property determines whether the items in the control will be automatically sorted. The control sorts each level of nodes separately. In our Globe example, it will sort the continents, then the countries within each continent, and then the cities within each country. Adding Nodes at Design Time Let’s look now at the process of populating the TreeView control. Adding an initial collection of nodes to a TreeView control at design time is trivial. Locate the Nodes property in the Properties window, and you’ll see that its value is Collection. To add items, click the ellipsis button, and the TreeNode Editor dialog box will appear, as shown in Figure 9.7. To add a root item, just click the Add Root button. The new item will be named Node0 by default. You can change its caption by selecting the item in the list and setting its Text property accordingly. You can also change the node’s Name property, as well as the node’s appearance by using the NodeFont, FontColor,and ForeColor properties. Figure 9.7 The TreeNode Editor dialog box To specify an image for the node, set the control’s ImageList property to the name of an ImageList control that contains the appropriate images, and then set either the node’s ImageKey property to the name of the image, or the node’s ImageIndex property to the index of the desired image in the ImageList control. If you want to display a different image when the control is selected, set the SelectedImageKey or the SelectedImageIndex property accordingly. You can add root items by clicking the Add Root button, or you can add items under the selected node by clicking the Add Child button. Follow these steps to enter the root node with the string Globe, a child node for Europe, and two more nodes under Europe: Germany and Italy. I’m assuming that you’re starting with a clean control. If your TreeView control contains any items, clear them all by selecting one item at a time in the list and pressing the Delete key, or clicking the delete button (the one with the X icon) on the dialog box. Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 313 THE TREEVIEW CONTROL 313 Click the Add Root button first. A new node is added automatically to the list of nodes, and it is named Node0. Select it with the mouse, and its properties appear in the right pane of the TreeNode Editor window. Here you can change the node’s Text property to GLOBE. You can specify the appearance of each node by setting its font and fore/background colors. Then click the Add Child button, which adds a new node under the GLOBAL root node. Select it with the mouse as before, and change its Text property to Europe. Then select the newly added node in the list and click the Add Child button again. Name the new node Germany.You’ve successfully added a small hierarchy of nodes. To add another node under Europe, select the Europe node in the list and click the Add Child button again. Name the new item Italy. Continue adding a few cities under each country. You might add child nodes under the wrong parent, which can happen if you forget to select the proper parent node before clicking the Add Child button. To delete a node, select it with the mouse and click the Delete button. Note that when a node is deleted, all the nodes under it are deleted, too. Moreover, this action can’t be undone. So be careful when deleting nodes. Click the OK button to close the TreeNode Editor’s window and return to your form. The nodes you added to the TreeView control are there, but they’re collapsed. Only the root nodes are displayed with the plus sign in front of their names. Click the plus sign to expand the tree and see its child nodes. The TreeView control behaves the same at design time as it does at runtime — as far as navigating the tree goes, at least. The nodes added to a TreeView control at design time will appear each time the form is loaded. You can add new nodes through your code, and you will see how this is done in the following section. Adding Nodes at Runtime Adding items to the control at runtime is a bit more involved. All the nodes belong to the control’s Nodes collection, which is made up of TreeNode objects. To access the Nodes collection, use the following expression, where TreeView1 is the control’s name and Nodes is a collection of TreeNode objects: TreeView1.Nodes This expression returns a collection of TreeNode objects and exposes the proper members for accessing and manipulating the individual nodes. The control’s Nodes property is the collection of all root nodes. To access the first node, use the expression TreeView.Nodes(0) (thisistheGlobenodeinour example). The Text property returns the node’s value, which is a string. TreeView1.Nodes(0). Text is the caption of the root node on the control. The caption of the second node on the same level is TreeView1.Nodes(1).Text,andsoon. The following statements print the strings shown highlighted below them (these strings are not part of the statements; they’re the output that the statements produce): Debug.WriteLine(TreeView1.Nodes(0).Text) GLOBE Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Text) Europe Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Nodes(1).Text) Italy Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 314 314 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS Let’s take a closer look at these expressions. TreeView1.Nodes(0) is the first root node, the Globe node. Under this node, there is a collection of nodes, the TreeView1.Nodes(0).Nodes collection. Each node in this collection is a continent name. The first node in this collection is Europe, and you can access it with the expression TreeView1.Nodes(0).Nodes(0).Ifyouwant to change the appearance of the node Europe, type a period after the preceding expression to access its properties (the NodeFont property to set its font, the ForeColor property to set it color, the ImageIndex property, and so on). Likewise, this node has its own Nodes collection, which contains the countries under the specific continent. Adding New Nodes The Add method adds a new node to the Nodes collection. The Add methodacceptsasanargument a string or a TreeNode object. The simplest form of the Add method is newNode = Nodes.Add(nodeCaption) where nodeCaption is a string that will be displayed on the control. Another form of the Add method allows you to add a TreeNode object directly (nodeObj is a properly initialized TreeNode variable): newNode = Nodes.Add(nodeObj) To use this form of the method, you must first declare and initialize a TreeNode object: Dim nodeObj As New TreeNode nodeObj.Text = ”Tree Node” nodeObj.ForeColor = Color.BlueViolet TreeView1.Nodes.Add(nodeObj) The last overloaded form of the Add method allows you to specify the index in the current Nodes collection, where the node will be added: newNode = Nodes.Add(index, nodeObj) The nodeObj TreeNode object must be initialized as usual. To add a child node to the root node, use a statement such as the following: TreeView1.Nodes(0).Nodes.Add(”Asia”) To add a country under Asia, use a statement such as the following: TreeView1.Nodes(0).Nodes(1).Nodes.Add(”Japan”) The expressions can get quite lengthy. The proper way to add child items to a node is to create a TreeNode variable that represents the parent node, under which the child nodes will be added. Let’s say that the ContinentNode variable in the following example represents the node Europe: Dim ContinentNode As TreeNode ContinentNode = TreeView1.Nodes(0).Nodes(2) Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 315 THE TREEVIEW CONTROL 315 Then you can add child nodes to the ContinentNode node: ContinentNode.Nodes.Add(”France”) ContinentNode.Nodes.Add(”Germany”) To add yet another level of nodes, the city nodes, create a new variable that represents a specific country. The Add method actually returns a TreeNode object that represents the newly added node, so you can add a country and a few cities by using statements such as the following: Dim CountryNode As TreeNode CountryNode = ContinentNode.Nodes.Add(”Germany”) CountryNode.Nodes.Add(”Berlin”) CountryNode.Nodes.Add(”Frankfurt”) Then you can continue adding countries under another continent as follows: CountryNode = ContinentNode.Nodes.Add(”Italy”) CountryNode.Nodes.Add(”Rome”) The Nodes Collection Members The Nodes collection exposes the usual members of a collection. The Count property returns the number of nodes in the Nodes collection. Again, this is not the total number of nodes in the control, just the number of nodes in the current Nodes collection. The expression TreeView1.Nodes.Count returns the number of all nodes in the first level of the control. In the case of the Globe example, it returns the value 1. The expression TreeView1.Nodes(0).Nodes.Count returns the number of continents in the Globe example. Again, you can simplify this expression by using an intermediate TreeNode object: Dim Continents As TreeNode Continents = TreeView1.Nodes(0) Debug.WriteLine( ”There are ” & Continents.Nodes.Count.ToString & ” continents on the control”) The Clear method removes all the child nodes from the current node. If you apply this method to the control’s root node, it will clear the control. To remove all the cities under the Germany node, use a statement such as the following: TreeView1.Nodes(0).Nodes(2).Nodes(1).Nodes.Clear This example assumes that the third node under Globe corresponds to Europe, and the second node under Europe corresponds to Germany. Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 316 316 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS The Item property retrieves a node specified by an index value. The expression Nodes.Item(1) is equivalent to the expression Nodes(1). Finally, the Remove method removes a node from the Nodes collection. Its syntax is Nodes.Remove(index) where index istheorderofthenodeinthecurrentNodes collection. To remove the selected node, call the Remove method on the SelectedNode property without arguments: TreeView1.SelectedNode.Remove Or you can apply the Remove method to a TreeNode object that represents the node you want to remove: Dim Node As TreeNode Node = TreeView1.Nodes(0).Nodes(7) Node.Remove There are four properties that allow you to retrieve any node at the current segment of the tree: FirstNode, NextNode, PrevNode,andLastNode. Let’s say the current node is the Germany node. The FirstNode property will return the first city under Germany (the first node in the current segment of the tree), and LastNode will return the last city under Germany. PrevNode and NextNode allow you to iterate through the nodes of the current segment: They return the next and previous nodes on the current segment of the tree (the sibling nodes, as they’re called). See the section called ‘‘Enumerating the Nodes Collection’’ later in this chapter for an example. Basic Nodes Properties There are a few properties you will find extremely handy as you program the TreeView control. The IsVisible property is a True/False value indicating whether the node to which it’s applied is visible. To bring an invisible node into view, call its EnsureVisible method: If Not TreeView1.SelectedNode.IsVisible Then TreeView1.EnsureVisible End If How can the selected node be invisible? It can, if you select it from within your code in a search operation. The IsSelected property returns True if the specified node is selected, while the IsExpanded property returns True if the specified node is expanded. You can toggle a node’s state by calling its Toggle method. You can also expand or collapse a node by calling its Expand or Collapse method, respectively. Finally, you can collapse or expand all nodes by calling the CollapseAll or ExpandAll method of the TreeView control. VB 2008 at Work: The TreeViewDemo Project It’s time to demonstrate the members discussed so far with an example. The project you’ll build in this section is the TreeViewDemo project. The project’s main form is shown in Figure 9.6. The Add Categories button adds the three top-level nodes to the TreeView control via the statements shown in Listing 9.1. These are the control’s root nodes. The other two Add buttons add nodes under the root nodes. Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 317 THE TREEVIEW CONTROL 317 Listing 9.1: The Add Categories Button Protected Sub AddCategories Click( ) Handles AddCategories.Click TreeView1.Nodes.Add(”Shapes”) TreeView1.Nodes.Add(”Solids”) TreeView1.Nodes.Add(”Colors”) End Sub When these statements are executed, three root nodes are added to the list. After clicking the Add Categories button, your TreeView control looks like the one shown here. To add a few nodes under the node Colors, you must retrieve the Colors Nodes collection and add child nodes to this collection, as shown in Listing 9.2. Listing 9.2: The Add Colors Button Protected Sub AddColors Click( ) Handles AddColors.Click Dim cnode As TreeNode cnode = TreeView1.Nodes(2) cnode.Nodes.Add(”Pink”) cnode.Nodes.Add(”Maroon”) cnode.Nodes.Add(”Teal”) End Sub When these statements are executed, three more nodes are added under the Colors node, but the Colors node won’t be expanded. Therefore, its child nodes won’t be visible. To see its child nodes, you must double-click the Colors node to expand it (or click the plus sign in front of it, if there is one). The same TreeView control with its Colors node expanded is shown to the left. Alternatively, you can add a statement that calls the Expand method of the cnode object, after adding the color nodes to the control: cnode.Expand() Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 318 318 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS Run the project, click the first button (Add Categories), and then click the second button (Add Colors). If you click the Add Colors button first, you’ll get a NullReferenceException, indicating that the node can’t be inserted unless its parent node already exists. I added a few statements in the TreeViewDemo project’s code to disable the buttons that generate similar runtime errors. To add child nodes under the Shapes node, use the statements shown in Listing 9.3. This is the Add Shapes button’s Click event handler. Listing 9.3: The Add Shapes Button Protected Sub AddShapes Click( ) Handles AddShapes.Click Dim snode As TreeNode snode = treeview1.Nodes(0) snode.Nodes.Add(”Square”) snode.Nodes.Add(”Triangle”) snode.Nodes.Add(”Circle”) End Sub If you run the project and click the three buttons in the order in which they appear on the form, the TreeView control will be populated with colors and shapes. If you double-click the items Colors and Shapes, the TreeView control’s nodes will be expanded. Notice that the code knows the order of the root node to which it’s adding child nodes. This approach doesn’t work with a sorted tree. If your TreeView control is sorted, you must create a hierarchy of nodes explicitly by using the following statements: snode = TreeView1.Nodes.Add(”Shapes”) snode.Add(”Square”) snode.Add(”Circle”) snode.Add(”Triangle”) These statements will work regardless of the control’s Sorted property setting. The three shapes will be added under the Shapes node, and their order will be determined automatically. Of course, you can always populate the control in any way you like and then turn on the Sorted property. Petroutsos c09.tex V2 - 01/28/2008 1:28pm Page 319 THE TREEVIEW CONTROL 319 Inserting a Root Node Let’s revise the code we’ve written so far to display all the nodes under a new header. In other words, we’ll add a new node called Items that will act as the root node for existing nodes. It’s not a common operation, but it’s an interesting example of how to manipulate the nodes of a TreeView control at runtime. First, we must add the new root node. Before we do so, however, we must copy all the first-level nodes into local variables. We’ll use these variables to add the current root nodes under the new (and single) root node. There are three root nodes currently in our control, so we need three local variables. The three variables are of the TreeNode type, and they’re set to the root nodes of the original tree. Then we must clear the entire tree, add the new root node (the Items node), and finally add all the copied nodes under the new root. The code behind the Move Tree button is shown in Listing 9.4. Listing 9.4: Moving an Entire Tree Protected Sub MoveTree Click( ) Handles bttnMoveTree.Click Dim colorNode, shapeNode, solidNode As TreeNode colorNode = TreeView1.Nodes(0) shapeNode = TreeView1.Nodes(1) solidNode = TreeView1.Nodes(2) TreeView1.Nodes.Clear() TreeView1.Nodes.Add(”Items”) TreeView1.Nodes(0).Nodes.Add(colorNode) TreeView1.Nodes(0).Nodes.Add(shapeNode) TreeView1.Nodes(0).Nodes.Add(solidNode) End Sub You can revise this code so that it uses an array of Node objects instead of individual variables to store all the root nodes. For a routine that will work with any tree, you must assume that the number of nodes is unknown, so the ArrayList would be a better choice. The following loop stores all the root nodes of the TreeView1 control to the TVList ArrayList: Dim TVList As New ArrayList Dim node As TreeNode For Each node in TreeView1.Nodes TVList.Add(node) Next Likewise, the following loop extracts the root nodes from the TVList ArrayList: Dim node As TreeNode Dim itm As Object TreeView1.Nodes.Clear For Each itm In TVList node = CType(itm, TreeNode) [...]... headers, all having the same width: Dim LWidth As Integer LWidth = ListView1.Width - 5 ListView1.ColumnHeaders.Add(”Company”, LWidth / 4) ListView1.ColumnHeaders.Add(”Contact”, LWidth / 4) ListView1.ColumnHeaders.Add(”Phone”, LWidth / 4) ListView1.ColumnHeaders.Add(”FAX”, LWidth / 4) ListView1.View = DetailsView This subroutine sets up four headers of equal width The first header corresponds to the item (not... 030-00 743 21 FAX 030-0076 545 Around the Horn Company Around the Horn Contact Hardy Thomas Telephone (171) 555-7788 FAX (171) 555-6750 The code in Listing 9.13 uses a For .Next loop to iterate through the items of the control You can also set up a For Each .Next loop, as shown here: Dim LI As ListViewItem For Each LI In ListView1.Items { access the current item through the LI variable} Next 339 340 CHAPTER... expand any folder in this pane and view its subfolders To view the files in a folder, click the folder name, and the right pane will be populated with the names of the selected folder’s files, along with 343 344 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS other data, such as the file size, date of creation, and date of last modification You haven’t seen the classes for accessing folders and files yet, but you... and three subitems to the ListView1 control: Dim LItem As ListViewItem LItem = ListView1.Items.Add(”Alfred’s Futterkiste”) LItem.SubItems.Add(”Maria Anders”) LItem.SubItems.Add(”030-00 743 21”) LItem.SubItems.Add(”030-0076 545 ”) To access the SubItems collection, you need a reference to the item to which the subitems belong The Add method returns a reference to the newly added item, the LItem variable, which... comparers Each comparer must be implemented in its own class, and you assign the name of the custom comparer to the ListViewItem property of the control Listing 9. 14 shows the ListCompanyComparer and ListContactComparer classes Listing 9. 14: The Two Custom Comparers for the ListViewDemo Project Class ListCompanySorter Implements IComparer Public Function CompareTo(ByVal o1 As Object, ByVal o2 As Object)... ListView1.ListViewItemSorter = New ListCompanySorter() ListView1.Sorting = SortOrder.Ascending Case 1 ListView1.LisViewtItemSorter = New ListContactSorter() ListView1.Sorting = SortOrder.Ascending End Select End Sub 341 342 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS Processing Selected Items The user can select multiple items from a ListView control by default Even though you can display a check mark in front of each... ListView1.Items.Add(”Customer 1”) LI.SubItems.Add(”Paul Levin”) LI.SubItems.Add(”NE”) LI.SubItems.Add(”12,100.90”) LI = ListView1.Items.Add(””) LI.SubItems.Add(””) LI.SubItems.Add(””) LI.SubItems.Add(”7 ,48 9.30”) LI.SubItems.Add((12100.9 - 748 9.3).ToString(”#,###.00”)) If your code reacts to the selection of an item with the mouse, or the double-click event, you must take into consideration that users may click an auxiliary... database Listing 9.12: Populating a ListView Control Dim LItem As New ListViewItem() LItem.Text = ”Alfred’s Futterkiste” LItem.SubItems.Add(”Anders Maria”) LItem.SubItems.Add(”030-00 743 21”) LItem.SubItems.Add(”030-0076 545 ”) LItem.ImageIndex = 0 ListView1.Items.Add(LItem) LItem = New ListViewItem() LItem.Text = ”Around the Horn” LItem.SubItems.Add(”Hardy Thomas”) LItem.SubItems.Add(”(171) 555-7788”)... font if you specify one by using the Font property of the corresponding subitem (see the section titled ‘‘The SubItems Collection,’’ later in this chapter) By default, subitems inherit the style of the basic item To use a different style for the subitems, set the item’s UseItemStyleForSubItems property to False Text property This property indicates the caption of the current item or subitem SubItems... you attach to it will be inserted automatically in alphabetical order If you reset the Sorted property to False, any child nodes you attach will be appended to the end of the existing sorted nodes VB 2008 at Work: The Globe Project The Globe project demonstrates many of the techniques we’ve discussed so far It’s not the simplest example of a TreeView control, and its code is lengthy, but it will help . c09.tex V2 - 01/28 /2008 1:28pm Page 311 THE TREEVIEW CONTROL 311 Figure 9.6 The TreeViewDemo project demonstrates the basic properties and methods of the TreeView control. Here are the basic properties. produce): Debug.WriteLine(TreeView1.Nodes(0).Text) GLOBE Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Text) Europe Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Nodes(1).Text) Italy Petroutsos c09.tex V2 - 01/28 /2008 1:28pm Page 3 14 3 14 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS Let’s take a closer look at these expressions expand a node, call the selected node’s Expand method. Petroutsos c09.tex V2 - 01/28 /2008 1:28pm Page 3 24 3 24 CHAPTER 9 THE TREEVIEW AND LISTVIEW CONTROLS Processing Multiple Selected Nodes The