- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
768 Chapter 16 THE TREEVIEW AND LISTVIEW CONTROLS
is positive, then we scan all the items of the Node.Nodes collection. To do this, the ScanNode() subroutine must call itself by passing a different argument. If you’re familiar with recursive procedures, you’ll find the code quite simple. If not, this coding probably will raise many questions. You can use the ScanNode() subroutine as is to scan any TreeView control. All you need is a reference to the root node (or the node you want to scan recursively), which you must pass to the ScanNode() subroutine as an argument. The subroutine will scan the entire subtree and display its nodes on a ListBox control. The nodes will be printed one after the other. To make the list easier to read, indent the names of the nodes by an amount that’s proportional to the levels of nesting. Nodes of the first level aren’t indented at all. Nodes on the first level can be indented by 5 spaces, nodes on the second level can be indented by 10 spaces, and so on. The variable IndentLevel keeps track of the level of nesting and is used to specify the indentation of the corresponding node. It’s increased by 5 when we start scanning a new subordinate node and decreased by the same amount when we return to the next level up. The IndentLevel variable is declared as Static so that it maintains its value between calls.
Run the TreeViewScan project and expand all nodes. Then click the Scan Tree button to populate the list on the right with the names of the continents/countries/cities. Obviously, the ListBox control is not a substitute for the TreeView control. The data have no particular structure; even when they’re indented, there are no tree lines connecting its nodes, and users can’t expand and collapse the control’s contents. So why bother to map the contents of the TreeView control to a ListBox control? The goal was to demonstrate how to scan a tree structure and extract all the nodes along with their structure.
You can use the ScanNode() subroutine to store the nodes of a TreeView control to a disk file or transfer them to a database or another control. The ScanNode() subroutine is the core of the subroutine you need and can be adjusted to accommodate any of the operations just mentioned.
The ListView Control
The ListView control is similar to the ListBox control except that it can display its items in many forms, along with any number of subitems for each item. To use the ListView control in your project, place an instance of the control on a form and then sets its basic properties, which are described in the following sections.
The View and Arrange properties There are two properties that determine how the various items will be displayed on the control: the View property, which determines how the items will appear, and the Arrange property, which determines how the items will be aligned on the control’s surface. The View property can have one of the values shown in Table 16.1.
Table 16.1: Settings of the View Property
Setting |
Description |
LargeIcon |
(Default) Each item is represented by an icon and a caption below the icon. |
SmallIcon |
Each item is represented by a small icon and a caption that appears to the right of the icon. |
List |
Each item is represented by a caption. |
Report |
Each item is displayed in a column with its subitems in adjacent columns. |
|
|
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
THE LISTVIEW CONTROL 769
The Arrange property determines how the items will be arranged on the control, and its possible settings are show in Table 16.2.
Table 16.2: Settings of the Arrange Property
Setting |
Description |
Default |
When an item is moved on the control, it remains where it is dropped. |
Left |
Items are aligned to the left side of the control. |
SnapToGrid |
Items are aligned to an invisible grid on the control. When the user moves an item, the item |
|
moves to the closest grid point on the control. |
Top |
Items are aligned to the top of the control. |
|
|
HeaderStyle This property determines the style of the headers in Report view. It has no meaning when the View property is set to something else, because only the Report view has columns. The possible settings for the HeaderStyle property are shown in Table 16.3.
Table 16.3: Settings of the HeaderStyle Property
Setting |
Description |
Clickable |
Visible column header that responds to clicking |
Nonclickable |
Visible column header that does not respond to clicking |
None |
No visible column header |
|
|
AllowColumnReorder This property is a True/False value that determines whether the user can reorder the columns at runtime. If this property is set to True, then the user can move a column to a new location by dragging its header with the mouse and dropping it in the place of another column. This property is also meaningful only in Report view.
Activation This property specifies the action that will activate an item on the control, and it can have one of the values shown in Table 16.4.
Table 16.4: Settings of the Activation Property
Setting |
Description |
OneClick |
Items are activated with a single click. When the cursor is over an item, it changes shape and |
|
the color of the item’s text changes. |
Standard |
Items are activated with a double-click. No change in the selected item’s text color takes |
|
place. |
TwoClick |
Items are activated with a double-click and their text changes color as well. |
|
|
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
770 Chapter 16 THE TREEVIEW AND LISTVIEW CONTROLS
FullRowSelect This property is a True/False value indicating whether the user can select an entire row or just the item’s text, and it’s meaningful only in Report view.
GridLines Another True/False property. If True, then grid lines between items and subitems are drawn. This property is meaningful only in Report view.
LabelEdit The LabelEdit property lets you specify whether the user will be allowed to edit the text of the items. The default value of this property is False.
MultiSelect A True/False value indicating whether the user can select multiple items on the control or not. To select multiple items, click them with the mouse while holding down the Shift or the Control key.
Scrollable A True/False value that determines whether the scrollbars are visible or not. Even if the scrollbars are invisible, users will still be able to bring any item into view. All they have to do is select an item and then press the arrow keys as many times as needed to scroll a different section of the Items collection into view.
Sorting This property determines how the items will be sorted, and as usual it’s meaningful only in Report view. This Sorting property isn’t a simple True/False value like the Sorted property of the TreeView control. Its setting can be None, Ascending, or Descending. A ListView control can be sorted in many ways (it has multiple columns), and each column may hold data of a different type. You must build a custom comparer and assign it to the ListViewItemSorter property of the ListView control. The process of sorting a ListView control is discussed in detail in the section “Sorting the ListView Control,” later in this chapter.
The Columns Collection
To display items in Report view, you must first set up the appropriate columns. The first column corresponds to the item, and the following columns correspond to its subitems. If you don’t set up at least one column, no items will be displayed in Report view. Conversely, the Columns collection is meaningful only when the ListView control is used in Report view.
The items of the Columns collection are of the ColumnHeader type. The simplest method to set up the appropriate columns is to do so at design time with a visual tool. Locate and select the Columns property in the Properties window, and click the button with the ellipses next to it. The ColumnHeader Collection Editor window will appear, as shown in Figure 16.11, where you can add and edit the appropriate columns.
Adding columns to a ListView control and setting their properties through the window of Figure 16.11 is quite trivial. Don’t forget to size the columns according to the data you anticipate to store in them and set their headers.
It is also possible to manipulate the Columns collection from within your code, with the methods and properties discussed here.
Add method Use the Add method of the Columns collection to add a new column to the control. The syntax of the Add method is
TreeView.Columns.Add(header, width, textAlign)
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
THE LISTVIEW CONTROL 771
Figure 16.11
The ColumnHeader Collection Editor window
The header argument is the column’s header (the string that appears on top of the items). The width argument is the column’s width in pixels, and the last argument determines how the text will be aligned. The textAlign argument can be Center, Justify, Left, NotSet, or Right. The NotSet setting specifies that horizontal alignment is not set.
The Add method returns a ColumnHeader object, which you can use later in your code to manipulate the corresponding column. The ColumnHeader object exposes a Name property, which can’t be set with the Add method.
Header1 = TreeView1.Add(“Column 1”, 60, ColAlignment.Left)
Header1.Name = “COL1”
After the execution of these statements, the first column can be accessed not only by index but by name as well.
Clear method This method removes all columns.
Count property This property returns the number of columns in the ListView control. You can add more subitems than there are columns in the control, but the excess subitems will not be displayed.
Remove method This method removes a column by its index:
ListView1.Columns(3).Remove
The indices of the following columns are automatically decreased by one.
The ListItem Object
As with the TreeView control, the ListView control can be populated either at design time or at runtime. To add items at design time, click the button with the ellipsis next to the ListItems property in the Properties window. When the ListViewItem Collection Editor window pops up, you can enter the items, including their subitems, as shown in Figure 16.12.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
772 Chapter 16 THE TREEVIEW AND LISTVIEW CONTROLS
Figure 16.12
The ListViewItem
Collection Editor
Click the Add button to add a new item. Each item has subitems, which you can specify as members of the SubItems collection. To add an item with three subitems, you can populate the SubItems collection with the appropriate elements. Click the button with the ellipsis in the SubItems property on the ListViewItem Collection Editor, and the ListViewSubItem Collection Editor will appear.
This window is very similar to the ListViewItem Collection Editor window, and you can add each item’s subitems. Assuming that you have added the item called Item 1 in the ListViewItem Collection Editor, you can add these subitems: Item 1-a, Item 1-b, and Item 1-c. The first subitem (the one with zero index) is actually the main item of the control.
Notice that you can set other properties, like the color and font for each item, the check box in front of the item that indicates whether the item is selected, and the image of the item. Use this window to experiment with the appearance of the control and the placement of the items, especially in Report view, since subitems are visible only in this view. Even then, you won’t see anything unless you specify headers for the columns.
Unlike the TreeView control, the ListView control allows you to specify a different appearance for each item and each subitem. To set the appearance of the items, use the Font, BackColor, and ForeColor properties of the ListViewItem object.
Almost all ListViews are populated at runtime. Not only that, but you should be able to add and remove items during the course of the application. The items of the ListView control are of the ListViewItem type, and they expose a number of members that allow you to control the appearance of the items on the control. These members are listed next:
BackColor property This property sets or returns the background color of the current item.
Checked property This property controls the status of an item. If it’s True, then the item has been selected. You can also select an item from within your code by setting its Checked property to True. The check boxes in front of each item won’t be visible unless you set the control’s CheckBoxes property to True.
Font property This property sets the font of the current item. Subitems can be displayed in a different font if you specify one with the SetSubItemFont method (see the section “The SubItems Collection,” later in this chapter).
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
