perfectxml.com
Focus Info Bank Free Library Software News About Us
  You are here: home »» Free Library » Syngress Publishing Saturday, 23 February 2008

Sample Chapter from the book VB.NET Developer's Guide. Reprinted by permission, Syngress Publishing © 2002.

Chapter 8

Windows Forms Components and Controls

Solutions in this chapter:

·     Built-In Controls

·     Creating Custom Windows Components

·     Creating Custom Windows Controls

·  Summary

·  Solutions Fast Track

·  Frequently Asked Questions

Introduction

Now that we have learned how to work with Windows Forms, we will take a look at Windows Controls. Visual Basic .NET comes with an extensive amount of built-in controls for use in your applications. This allows applications to be developed more rapidly. There are controls for displaying labels, allowing user input of text, and working with numbers. There are controls for users to make choices, and various ways of displaying information to the user. As in previous versions of Visual Basic, you can also use controls created by third-party vendors. This allows you great flexibility in utilizing the controls that best fit your needs. Controls are manipulated by their properties and methods. A control can be configured at design time with its design-time properties and further controlled at runtime with its runtime properties and methods.

So what do you do if you can’t find a control that does exactly what you need? One option is to compromise and accept the control(s) closest to your needs. This is not always acceptable, however. In Visual Basic .NET, you will still have the ability to develop your own custom-made controls, which allows you to create the exact desired functionality. You can even develop your own control to become one of those third-part vendors that sell controls. You can create design-time properties as well as runtime properties and methods to provide the developer with access to manipulate your control. You even have the ability to bind your control to a data source.

You don’t always need to have controls with a GUI. Sometimes you just want to create a component that only provides programmatic functionality. This allows you to create libraries or objects that greatly facilitate reuse of code. You also might need a middle-tier component to provide business logic for a multi-tier application. This is what Windows components are for. These are similar to Visual Basic 6.0 ActiveX DLLs. Whatever the needs of your application, you can use existing controls as necessary, or develop your own custom controls and components.

Built-In Controls

Visual Basic .NET offers numerous controls you can use to build an application. Each of these controls has a particular function. In some cases, you can choose more than one control to achieve the results you want. For example, if you want to display text that cannot be edited by the user, you can use a label, link label, read-only text box, or read-only rich text box. However, we will see in this chapter that not all of these allow the user to copy text to the Clipboard, and only one of these displays a bulleted list of items.

It is important to familiarize yourself with the built-in controls and their general functions so you can choose the right control for a particular application. Knowing the limitations of the built-in controls also allows you to identify applications for which no built-in control is appropriate. These applications call for custom Windows controls.

In this section, we will look closely at a number of controls built into Visual Basic .NET. Table 8.1 displays the controls discussed in this chapter according to their general function.

Table 8.1 Windows Forms Controls by Function

Control

Function

Informational Only

 

Label

Displays text that cannot be edited by the user

LinkLabel

Displays text that is a link to another window or Web site

Text Edit

 

TextBox

Displays text that can be edited by the user

RichTextBox

Displays text in Rich Text Format (RTF)

Selection from List

 

ComboBox

Displays a drop-down list of items

DomainUpDown

Displays a list of text items through which the user can scroll with a spin button

NumericUpDown

Displays a list of numeric items through which the user can scroll with a spin button

ListBox

Displays a list of items

ListView

Displays text in a text-only, text-with-small-icons, text-with-large-icons, or report view

TreeView

Displays hierarchical information

Graphics Display

 

PictureBox

Displays graphics

Value Setting

 

CheckBox

Presents options that are not mutually exclusive

CheckedListBox

Displays a list of items, each along with a check mark

RadioButton

Presents mutually exclusive options

TrackBar

Displays a scale on which the user can set a value

Date Setting

 

DateTimePicker

Displays a graphical calendar from which the user can set a date

Command Controls

 

Button

Starts, stops, or interrupts a process

Grouping Controls

 

Panel

Holds a scrollable group of controls

GroupBox

Holds a captioned group of controls

Tab

Provides a tabbed page for organizing and efficiently accessing grouped objects

There are some properties that are shared by many controls, like the Name property, which indicates the name used in code to identify the object. Table 8.2 displays common properties of controls. As we look at each control in the following sections, we will discuss the properties unique to them.

Table 8.2 Common Properties of Controls

Property

Description

(Bindings)

This collection holds all the bindings of properties of this control to data sources

(Name)

Indicates the name used in code to identify the object

AccessibleDescription

The description that will be reported to accessibility clients

AccessibleName

The name that will be reported to accessibility clients

AccessibleRole

The role that will be reported to accessibility clients

Anchor

The anchor of the control. Anchors define to which edges of the container a certain control is bound. When a control is anchored to an edge, the distance between the control’s closest edge and the specified edge will remain constant

CausesValidation

Indicates whether this control causes and raises validation events

ContextMenu

The shortcut menu to display when the user right-clicks the control

Dock

The docking location of the control, indicating which borders are docked to the container

Enabled

Indicates whether the control is enabled

IMEMode

Determines the IME (Input Method Editor) status of the object when selected

Location

The position of the top-left corner of the control with respect to its container

Locked

Determines if the control can be moved or resized

Modifiers

Indicates the visibility level of the object

Size

The size of the control in pixels

Visible

Determines whether the control is visible or hidden

Label Control

The Windows Forms Label control allows you to display text that cannot be edited by the user. You can use labels to add descriptive captions to other controls to help identify their purpose. It is common practice to provide labels for controls that do not have a label themselves, such as text boxes, including a colon in the label's caption.

Labels cannot receive focus, but you can use labels to quickly move focus to other controls by creating access keys. When you use a label to create an access key, the user can press the Altkey, plus the character you designate, to move the focus to the control that follows the label in the tab order.

You can also use labels to display information about runtime events or processes in your application. For example, in an e-mail manager application, you can use a label to inform the user when your application is connecting to the mail server, checking for new messages, and disconnecting from the mail server. The Text property is the default property of a label. Table 8.3 shows other properties of the Label control.

Table 8.3 Label Properties

Property

Description

AllowDrop

Determines if the label will receive drag-drop notifications

AutoSize

Enables automatic resizing based on font size. Note that this is only valid for labels that don’t wrap text

BackColor

The background color used to display text and graphics in the label

BorderStyle

Determines if the label has a visible border

Cursor

The cursor that appears when the mouse passes over the label

Font

The font used to display text in the label

ForeColor

The foreground color used to display text and graphics in the label

Image

The image that will be displayed on the face of the label

ImageAlign

The alignment of the image that will be displayed in the face of the label

ImageIndex

The index of the image in the image list to display in the face of the label

ImageList

The image list to get the image to display in the face of the label

RightToLeft

Indicates whether the label should draw right-to-left for RTL languages

TabIndex

Determines the index in the tab order that this label will occupy

Text

The text contained in the label

TextAlign

Determines the position of the text within the label

UseMnemonic

If True, the first character preceded by an ampersand (&) will be used as the label’s mnemonic key

A foremost property of the Label control is the Text property, which contains the label's caption. In previous versions of Visual Basic, the Caption property was used to specify the text displayed in the label. As with most properties of the label, you can set the caption at design-time or runtime. To set a label's caption at design-time, use the Properties window to set the Text property to an appropriate string. To set a label's caption at runtime, set the Text property programmatically, as shown next:

'Set the label's caption

lblStatus.Text = "Finding Server..."

The AutoSize property helps you size a label to fit smaller or larger captions, which is useful if the caption changes run-time. Use the AutoSize property to fix the size of a label or make it dynamically resize to hold the value of the Text property. To make a label dynamically resize to hold its text, set the AutoSize property to True:

'Make the label dynamically resize to fit its contents

lblStatus.AutoSize = True

Note

If the AutoSize property is set to False, the text wraps to the next line, but the label does not grow.

The TextAlign property helps you change the horizontal alignment of text within a label. You can choose to align a label's caption with the left margin or right margin of the label, or to center the caption within a label's margins. For example, to center a label's caption within its margins, set the TextAlign property as shown in the following:

'Center text within the label's caption

lblStatus.TextAlign = HorizontalAlignment.Center

You can use labels to assign access keys to other controls. When you use a label to create an access key, the user can press the alt key, plus the character you designate, to move the focus to the control that follows the label in the tab order. Since labels cannot receive focus, focus automatically moves to the control that follows it in the tab order.

LinkLabel Control

The Windows Forms LinkLabel control allows you to add Web-style links to your Windows Forms applications. The LinkLabel control retains all properties, methods, and events of the Label control, and you can use a link label for everything with which you can use a label. In addition, the LinkLabel control allows you to set part of its caption as a link to an object or Web page. For instance, you can use a link label in the About box of your application to provide a link to your company's Web page. Table 8.4 shows the properties of the LinkLabel control, in addition to the properties of the Label control.

Table 8.4 LinkLabel Properties

Property

Description

ActiveLinkColor

Determines the color of the hyperlink when the user is clicking the link

DisabledLinkColor

Determines the color of the hyperlink when disabled

LinkArea

Portion of the text in the label to render as a hyperlink

LinkBehavior

Determines the underline behavior of the hyperlink

LinkColor

Determines the color of the hyperlink

LinkVisited

Determines if the hyperlink should be rendered as visited

VisitedLinkColor

Determines the color of the hyperlink when the LinkVisited property is set to True

The ActiveLinkColor, DisabledLinkColor, LinkColor, and VisitedLinkColor properties determine the color of the link. For example, when the link is clicked, you can change its color to indicate it has been visited. The LinkColor property determines the color of the link when it is in its default state—when the user is not clicking the link, the link is not disabled, and the link is not rendered as visited. When the user is clicking the link, its color is determined by the ActiveLinkColor property. The DisabledLinkColor property determines the color of the link when it is disabled. When the link is rendered as visited, the VisitedLinkColor property determines the color of the link. To change the color of a link using defined color constants, set the ActiveLinkColor, DisabledLinkColor, LinkColor, and VisitedLinkColor properties as shown next:

'Set the link color using defined color constants

with lnkWebSite

    .ActiveLinkColor = color.Red

    .DisabledLinkColor = color.Blue

    .LinkColor = color.Blue

    .VisitedLinkColor = color.Purple

end with

You can also change the color of a link using decimal values for red, green, and blue. For instance, you can change the color of the same link using decimal values for red, green, and blue as shown in the following:

'Set the link color using decimal values for red, green, and blue

With lnkWebSite

    .ActiveLinkColor = Color.FromARGB(255, 0, 0)

    .DisabledLinkColor = Color.FromARGB(0, 0, 255)

    .LinkColor = Color.FromARGB(0, 0, 255)

    .VisitedLinkColor = Color.FromARGB(128, 0, 128)

End With

The LinkArea property holds the portion of the link label's caption that activates the link. The LinkArea.X property determines the start of the link area, and the LinkArea.Y property determines the length of the link area. In the following example, the link area starts before the first character of the link label's caption, and ends after the last character of the caption:

'Set the link area to all of the caption

With lnkWebSite

    .LinkArea.X = 0

    .LinkArea.Y = Len(linklabel1.Text)

End With

You can choose, however, to only use part of the link label to activate the link. For example, to have only the third character of the caption to comprise the link area, set the LinkArea property as follows:

        With lnkWebSite

            .LinkArea.X = 3

            .LinkArea.Y = 1

        End With

It is common to indicate that a link can be clicked by showing an underline with the link. The LinkBehavior property determines when the link shows an underline, be it always, never, when the mouse hovers over the link, or the system default setting. For example, to set the link to always appear with an underline, set the LinkBehavior property as follows:

'Set the link to always appear with an underline

lnkWebSite.LinkBehavior = LinkBehavior.AlwaysUnderline

Another useful property of the link label is the LinkVisited property, which determines when the link is to be marked as visited. You may, for instance, have a link label on a form with which you want to display another form. After the second form is displayed, you want to give the user an indication that the form was displayed. To mark the link as visited in the color specified by the VisitedLinkColor property, set the LinkVisited property to True:

Protected Sub lnkWebSite_LinkClicked(ByVal sender As Object,

ByVal e As System.EventArgs)

    Dim frmDetails As New Form()

 

    'Display another form

    frmDetails.Show()

 

    'Mark the link as visited   

    lnkWebSite.LinkVisited = True

End Sub

The Click event of the link label is an important one, since the Click event determines what happens when the link is selected. Use the LinkClicked event handler to take appropriate action when the link is clicked. To start the default Web browser and link to a Web page:

1.   In the LinkClicked event handler, use the Process.Start method to start the default browser with a URL. To use the Process.Start method, you need to add a reference to the System.Diagnostics namespace.

2.   Set the LinkVisited property to True.

The following example shows how to start the default Web browser and link to the Microsoft Web site:

Private Sub lnkWebSite_LinkClicked (ByVal Sender As Object, _

ByVal e As EventArgs)

    'Open the default Web browser and link to the Microsoft Web site

    System.Diagnostics.Process.Start("http://www.microsoft.com")

 

    'Mark the link as visited

    lnkWebSite.LinkVisited = True

End Sub

TextBox Control

The Windows Forms TextBox control allows you to display text to the user and collect text from the user. You can also use text boxes to add basic formatting to your application such as password text boxes. A password text box is one that displays a placeholder character instead of each character entered. Text boxes can display multiple lines. By default, a text box holds up to 2,048 characters, but when displaying multiple lines, a text box holds up to 32K of text. Text boxes are most commonly used for editable text, but they can also be made read-only. Table 8.5 shows the properties of the TextBox control.

Table 8.5 TextBox Properties

Property

Description

AcceptsReturn

Indicates if return characters are accepted as input for multiline edit controls

AcceptsTab

Indicates if tab characters are accepted as input for multiline edit controls

AutoSize

Enables automatic resizing based on font size for single-line edit controls

BackColor

The background color used to display text and graphics in the control

BorderStyle

Indicates whether or not the edit control should have a border

CharacterCasing

Indicates if all characters should be left alone or converted to uppercase or lowercase

Cursor

The cursor that appears when the mouse passes over the control

Font

The font used to display text in the control

ForeColor

The foreground color used to display text and graphics in the control

HideSelection

Indicates that the selection should be hidden when the edit control loses focus

Lines

The lines of text in a multiline edit, as in an array of string values

MaxLength

Specifies the maximum number of characters that can be entered into the edit control. Zero implies no maximum

MultiLine

Controls whether the text of the edit control can span more than one line

PasswordChar

Indicates the character to display for password input for single-line edit controls

ReadOnly

Controls whether the text in the edit control can be changed or not

RightToLeft

Indicates whether the control should draw right-to-left for RTL languages

ScrollBars

Indicates, for multi-line edit controls, which scroll bars will be shown for this control

TabIndex

Determines the index in the tab order that this control will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the control

Text

The text contained in the control

TextAlign

Indicates how the text should be aligned for edit controls

WordWrap

Indicates if lines are automatically word-wrapped for multi-line edit controls

Note

Use a Label control with the TextBox control to help the user identify the purpose of the TextBox control and to indicate when it is disabled.

You can display multiple lines in a TextBox control by using the MultiLine, WordWrap, and ScrollBars properties. To display multiple lines in a TextBox control:

1.   Set the MultiLine property to True.

2.   Set the ScrollBars property to None, Horizontal, or Both.

3.   Set the WordWrap property to False or True.

Now let’s see how this is done in code:

With txtTextBox

    'Set the MultiLine property to True

    .MultiLine = True

   

    'Set the ScrollBars property

    .ScrollBars = vbBoth

 

    'Set the WordWrap property

    .WordWrap = True

End With

You can create a read-only text box by using the ReadOnly property. If the ReadOnly property is set to True, the Copy command is available, but the Cut and Paste commands are unavailable.

Note

Create a read-only text box by using a TextBox control instead of a Label control when you want to allow the user to select the text. For example, if you use a TextBox control to create a read-only text box, the user can copy the text to the Clipboard.

You can use the MaxLength and PasswordChar properties to create a password text box that displays a placeholder character instead of each character entered. To create a password text box:

1.   Set the PasswordChar property to a placeholder character.

2.   Set the MaxLength property to the maximum number of characters allowed. If the user attempts to exceed this number, the system emits a beep and does not accept any more characters.

Now let’s see how this is done in code:

With txtTextBox

    'Set PasswordChar property to the asterisk

    .PasswordChar = "*"

   

    'Set the MaxLength property to 10

    .MaxLength = 10

End With

There are several ways to programmatically place quotation marks in the text of a TextBox control. You can use an additional set of quotation marks, use the ASCII character (34), or define a constant for the quotation marks character, as shown in the following example:

With txtTextBox

    'Insert an additional set of quotation marks

    .Text = """Wow, five!"" the woman said."

   

    'Use the ASCII character (34)

    .Text = Chr(34) & "Wow, five!" & Chr(34) _

        & " the woman said."

 

    'Define a constant for the quotation marks character

    Const strQuotationMarks = """"

 

    .Text = strQuotationMarks & "Wow, five!" _

        strQuotationMarks & " the woman said."

End With

The default insertion point for a Windows Forms TextBox control is to the left of any text when it first receives the focus. After the focus moves away from, and then back to, the TextBox control, the insertion point is at the position where the user last placed it. You can use the SelectionStart and SelectionLength properties to control the insertion point to, for instance, select all existing text to speed data entry:

With txtTextBox

    'Set the SelectionStart property to the left of any

    'text

    .SelectionStart = 0

   

    'Set the SelectionLength property to select all text

    .SelectionLength = Len(txtTextBox)

End With

Button Control

The Windows Forms Button control performs an action when the button is clicked, making it look as if the button is being pushed in and released. When the user clicks the button, the Click event handler is invoked. To respond to a button click, write code in the button’s Click event handler, as shown in the following example:

Private Sub btnCancel_Click(ByVal sender As _

    System.Object, ByVal e As System.EventArgs)

   frmForm.Hide()

End Sub

Note

The button does not support a double-click event. If the user attempts to double-click a button, its Click event handler will be invoked twice if the button is still visible and available after the first click.

Like the other controls we discussed, the Button has a number of properties that are not among the properties common to all built-in controls. Table 8.6 shows the properties of the Button control.

Table 8.6 Button Properties

Property

Description

BackColor

The background color used to display text and graphics in the control

BackgroundImage

The background image used for the control

Cursor

The cursor that appears when the mouse passes over the control

DialogResult

The dialog result produced in a modal form by clicking the button

FlatStyle

Determines the display of the button when users move the mouse over the control and click

Font

The font used to display text in the control

ForeColor

The foreground color used to display text and graphics in the control

Image

The image that will be displayed on the face of the control

ImageAlign

The alignment of the image that will be displayed in the face of the control

ImageIndex

The index of the image in the image list to display in the face of the control

ImageList

The image list to get the image to display in the face of the button

RightToLeft

Indicates whether the button should draw right-to-left for RTL languages

TabIndex

Determines the index in the tab order that the button will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the button

Text

The text contained in the button

TextAlign

The alignment of the text that will be displayed in the face of the button

The user can click the Button control in several ways:

·     The user uses a mouse to click the button.

·     The user chooses the button by pressing the Spacebar or Enter key when the button has the focus.

·     The user presses Enter when the button is the “accept” button of the form.

·     The user presses ESC when the button is the “cancel” button of the form.

·     The user presses the access key (Alt +the underlined letter) for the button.

In addition, you can click the Button control programmatically in the following ways:

·     Invoke the button's Click event.

·     Call the PerformClick method.

When you designate a Button control to be the accept button on the form, the button is clicked when the user presses Enter, even if another control has the focus—except when that other control is another button or a multiline text box. This basically makes it the default button on the form. When you designate a Button control to be the cancel button on the form, the button is clicked when the user presses ESC, even if another control has the focus. A button can be both the accept button and the cancel button on the form. The following code shows you how to do this:

With frmForm

    'Designate btnButton as the accept button and the

    'cancel button of frmForm

 

    'Set the AcceptButton property to btnButton

    .AcceptButton = btnButton

    

    'Set the CancelButton property to btnButton

    .CancelButton = btnButton

End With

Note

If the action represented by a Button control requires additional information, such as the folder in which to save a document, include an ellipsis (…) in the button’s Caption property.

CheckBox Control

The Windows Forms CheckBox control indicates True/False or Yes/No options. The CheckBox control appears as a square box with an accompanying label. When a choice is set, a check mark appears in the box. When the choice is not set, the box is empty. Use the CheckBox control to present an independent or non-exclusive choice, a True/False or Yes/No selection to the user. You can group multiple check boxes using a GroupBox control to display multiple choices from which the user may select more than one.

The CheckBox control has two important properties: Checked and CheckedState. The Checked property returns either True or False, and indicates whether the choice is set. The CheckedState property returns CheckState.Checked when the choice is set, and CheckState.Unchecked when the choice is not set. If the ThreeState property is set to True, the CheckedState property also returns CheckState.Indeterminate, used when the choice is set for some but not all elements of the selection.

Since grouped controls can be moved around together on the form designer, group multiple boxes using the GroupBox control to enhance visual appearance and aid in GUI design Table 8.7 shows the properties of the CheckBox control.

Table 8.7 CheckBox Properties

Property

Description

AllowDrop

Determines if the check box will receive drag-drop notifications

Appearance

Controls the appearance of the check box

AutoCheck

Causes the check box to automatically change state when clicked

BackColor

The background color used to display text and graphics in the check box

BackgroundImage

The background image used for the check box

CheckAlign

Determines the location of the check box inside the control

Checked

Indicates whether the check box is checked or unchecked

Cursor

The cursor that appears when the mouse passes over the check box

FlatStyle

Determines the display of the check box when users move the mouse over the check box and click

Font

The font used to display text in the check box

ForeColor

The foreground color used to display text and graphics in the check box

Image

The image that will be displayed on the face of the check box

ImageAlign

The alignment of the image that will be displayed in the face of the check box

ImageIndex

The index of the image in the image list to display in the face of the check box

ImageList

The image list to get the image to display in the face of the check box

RightToLeft

Indicates whether the check box should draw right-to-left for RTL languages

TabIndex

Determines the index in the tab order that the check box will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the check box

Text

The text contained in the check box

TextAlign

The alignment of the text that will be displayed in the face of the check box

ThreeState

Controls whether or not the user can select the indeterminate state of the check box

RadioButton Control

The Windows Forms RadioButton control is used to give the user a single choice within a set of two or more mutually exclusive choices. Radio buttons appear as a set of small circles. When an option button choice is set, a dot appears in the middle of the circle. When the item is not the current setting, the circle next to the current setting is empty. If the user chooses any radio button in a group, that value becomes the setting for the group; the dot appears in that button and all the other buttons in the group remain empty. Group radio buttons by adding them to a form. To add separate groups, you need to add them to a Panel control or a GroupBox control.

The radio button and the check box are used for different functions. Use a radio button when you want the user to choose only one option. When you want the user to choose all appropriate options, use a check box. Table 8.8 shows the properties of the RadioButton control.

Table 8.8 RadioButton Properties

Property

Description

AllowDrop

Determines if the radio button will receive drag-drop notifications

Appearance

Controls whether the radio button appears as normal or as a Windows push button

AutoCheck

Causes the radio button to automatically change state when clicked

BackColor

The background color used to display text and graphics in the radio button

BackgroundImage

The background image used for the radio button

CheckAlign

Determines the location of the check box inside the radio button

Checked

Indicates whether the radio button is checked or not

Cursor

The cursor that appears when the mouse passes over the radio button

FlatStyle

Determines the display of the radio button when users move the mouse over the radio button and click

Font

The font used to display text in the radio button

ForeColor

The foreground color used to display text and graphics in the radio button

Image

The image that will be displayed on the face of the radio button

ImageAlign

The alignment of the image that will be displayed in the face of the radio button

ImageIndex

The index of the image in the image list to display in the face of the radio button

ImageList

The image list to get the image to display in the face of the radio button

RightToLeft

Indicates whether the radio button should draw right-to-left for RTL languages

TabIndex

Determines the index in the tab order that the radio button will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the radio button

Text

The text contained in the radio button

TextAlign

The alignment of the text that will be displayed in the face of the radio button

RichTextBox Control

Much like the TextBox control, the Windows Forms RichTextBox control allows you to display text to the user and collect text from the user. In addition to the many features it shares with the TextBox control, the RichTextBox control allows you to change the font, size, and color of text. You can use a rich text box to add advanced formatting, such as indents, hanging indents, and bulleted paragraphs, to your application. You can also use a rich text box to save text to a file, or load text from a file. Table 8.9 shows the properties of the RichTextBox control.

Table 8.9 RichTextBox Properties

Property

Description

AcceptsTab

Indicates if tab characters are accepted as input for the rich text box

AutoSize

Enables automatic resizing based on font size for a single-line rich text box

AutoWordSelection

Turns on/off automatic word selection

BackColor

The background color used to display text and graphics in the rich text box

BorderStyle

Indicates whether or not the rich text box should have a border

BulletIndent

Defines the indent for the bullets in the rich text box

Cursor

The cursor that appears when the mouse passes over the rich text box

Delimiter

Defines the delimiter characters (Asian version of OS only)

DetectURLs

Turns on/off automatic URL highlighting

FollowPunctuation

Defines the non-leading punctuation (Asian version of OS only)

Font

The font used to display text in the rich text box

ForeColor

The foreground color used to display text and graphics in the rich text box

HideSelection

Indicates that the selection should be hidden when the rich text box loses focus

LeadPunctuation

Defines the leading punctuation (Asian version of OS only)

Lines

The lines of text in a multi-line rich text box, as in an array of string values

MaxLength

Specifies the maximum number of characters that can be entered into the rich text box. Zero implies no maximum

Multiline

Controls whether the text of the rich text box can span more than one line

OutlineMode

Turns on/off outline mode

ReadOnly

Controls whether the text in the rich text box can be changed or not

RightMargin

Defines the right margin dimensions

RightToLeft

Indicates whether the rich text box should draw right-to-left for RTL languages

ScrollBars

Defines the behavior of the scroll bars of the rich text box

SelectionMargin

Turns on/off the selection margin

TabIndex

Determines the index in the tab order that the rich text box will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the rich text box

Text

The text contained in the rich text box

WordBreak

Enables the word-break mode (Asian version of OS only)

WordPunctuation

Defines the type of punctuation table to be used for word operations (Asian version of OS only)

WordWrap

Indicates if lines are automatically word-wrapped for multi-line rich text boxes

 

You can change the font, size, and color of text in the RichTextBox control by using the SelFont, SelFontSize, and SelColor properties. Also, you can quickly open a Rich Text Format file using a rich text box. This is handy when you want your application to display a README file that changes with every version of your application. You make changes to the file, not your code, and you can simply open the file with a rich text box. Use an OpenFileDialog control to navigate to the file you want to open, as in the following example:

With OpenFileDialog1

    'Show only RTF files

    .Filter = "Rich Text Format|*.rtf"

    .ShowDialog()

End With

       

richtextbox2.LoadFile(openfiledialog1.FileName)

Often, when opening files, you only want to show those with a certain extension. This makes it easier for the user to locate a file. You can do this with the Filter property of the Open File dialog box:

.Filter = "Rich Text Format|*.rtf"

Use this line to show only RTF files in the Open File dialog box. Files with other extensions will not appear.

TreeView Control

The Windows Forms TreeView control is used to display hierarchical information, such as e-mail folders and messages, as well as folders and files on a computer. A tree view contains cascading branches of nodes, and each node consists of an image and a label. Node images are taken from an ImageList control. At the top-most level in a tree view are root nodes that can be expanded or collapsed if the nodes have child nodes (nodes that descend from other nodes). Table 8.10 shows the properties of the TreeView control:

Table 8.10 TreeView Properties

Property

Description

AllowDrop

Determines if the tree view will receive drag-drop notifications

BackColor

The background color used to display text and graphics in the tree view

BorderStyle

The border style of the tree view

CheckBoxes

Indicates whether check boxes are displayed beside nodes

Cursor

The cursor that appears when the mouse passes over the tree view

Font

The font used to display text in the tree view

ForeColor

The foreground color used to display text and graphics in the tree view

FullRowSelect

Indicates whether the highlight spans the width of the tree view

HideSelection

Removes highlight from the selected node when the tree view loses focus

HotTracking

Indicates whether nodes give feedback when the mouse is moved over them

ImageIndex

The default image index for nodes

ImageList

The image list from which node images are taken

Indent

The indentation width of child nodes in pixels

ItemHeight

The height of every item in the tree view

LabelEdit

Indicates whether or not the user can edit the label text of nodes

Nodes

The root nodes in the tree view

PathSeparator

The string delimiter used for the path returned by a node’s FullPath property

RightToLeft

Indicates whether the control should draw right-to-left for RTL languages

Scrollable

Indicates whether the tree view will display scroll bars if it contains more nodes than can fit in the visible area

SelectedImage

The default image index for selected nodes

ShowLines

Indicates whether lines are displayed between sibling nodes and between parent and child nodes

ShowPlusMinus

Indicates if plus/minus buttons are shown next to parent nodes

ShowRootLines

Indicates whether lines are displayed between root nodes

Sorted

Indicates whether nodes are sorted

TabIndex

Determines the index in the tab order that this control will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the tree view

ListBox Control

A Windows Forms ListBox control displays a list of choices which the user can select from. List boxes are best used for displaying large number of choices. There are situations in which you can display choices with either a group of check boxes or a list box. In general, use a group of check boxes when the number of choices is small. For clarity, use a list box when the number of choices is large.

A vertical scroll bar accompanies a list box if the items displayed exceed the height of the box. A list box will also sport a horizontal scrollbar if the MultiColumn property is set to True. In that case, values are displayed in columns horizontally. Table 8.11 shows the properties of the ListBox control:

Table 8.11 ListBox Properties

Property

Description

AllowDrop

Determines if the list box will receive drag-drop notifications

BackColor

The background color used to display text and graphics in the list box

BorderStyle

Controls what type of border is drawn around the list box

ColumnWidth

Indicates how wide each column should be in a multicolumn list box

Cursor

The cursor that appears when the mouse passes over the list box

DataSource

Indicates the list that the list box will use to get its items

DisplayMember

Indicates the property to display for the items in the list box

DrawMode

Indicates whether the system or the user paints items in the list box

Font

The font used to display text in the list box

ForeColor

The foreground color used to display text and graphics in the list box

HorizontalExtent

The width, in pixels, by which a list box can be scrolled horizontally. Only valid if HorizontalScrollbar is True

HorizontalScrollbar

Indicates whether the list box will display a horizontal scrollbar for items beyond the right edge of the list box

IntegralHeight

Indicates whether the list can contain only complete items

ItemHeight

The height, in pixels, of items in a fixed-height owner-drawn list box

Items

The items in the list box

MultiColumn

Indicates if values should be displayed in columns horizontally

RightToLeft

Indicates whether the list box should draw right-to-left for RTL languages

ScrollAlwaysVisible

Indicates if the list box should always have a scrollbar present, regardless of how many items are in it

SelectionMode

Indicates if the list box is to be single-select, multi-select, or unselectable

Sorted

Controls whether the list is sorted

TabIndex

Determines the index in the tab order that the list box will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the list box

UseTabStops

Indicates if tab characters should be expanded into full spacing

ValueMember

Indicates the property to use as the actual value for the items in the list box

 

The SelectionMode property determines how many items in the list can be selected at a time. If the SelectionMode property is set to SelectionMode.MultiSimple, the user can select more than one item by simply clicking the items in the list. If the SelectionMode property is set to SelectionMode.MultiExtended, the user can select more than one item by holding down the ctrl key or Shift key and clicking items in the list.

As with other controls, the SelectedIndex property holds the index of the selected item in the list box. If more than one item is selected, the SelectedIndex property contains the index of the first selected item in the box. Keep in mind that the SelectedIndex property is zero-based like other index properties in VB .NET. For example, the SelectedIndex property equals 0 when the first item in a list box is selected.

You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box. The Insert method allows you to specify where to insert the item you are adding. In the following example, the name “John Doe” is added to a list box first. Then the name “Jane Doe” is inserted at the first position in the list, rather than at the last position:

'Add the name "John Doe" to the Employees list box

lstEmployees.Items.Add("John Doe")

 

'Insert the name "Jane Doe" at the first position in the list box

lstEmployees.Items.Insert(0, "Jane Doe")

You can use the Remove method to remove an item from a list box. Continuing our example, the following statement removes the first name from the list box:

'Remove the first name from the Employees list box

lstEmployees.Items.Remove(0)

You can also quickly remove all items from a list box. To remove all items from a list box, simply use the Clear method of the Items collection.

'Remove all names from the Employees list box

lstEmployees.Items.Clear()

CheckedListBox Control

The Windows Forms CheckedListBox control, an extension of the ListBox control, gives you all the capability of a list box and also allows you to display a check mark next to the items in the list box. Use the checked list box instead of the list box to display additional information about the items you display. For example, a checked list box is a good choice to display steps of an installation, with the check marks indicating which steps have been completed. Table 8.12 shows the properties of the CheckedListBox control:

Table 8.12 CheckedListBox Properties

Property

Description

AllowDrop

Determines if the checked list box will receive drag-drop notifications

BackColor

The background color used to display text and graphics in the checked list box

BorderStyle

Controls what type of border is drawn around the checked list box

CheckOnClick

Indicates if the check box should be toggled with the first click of an item

ColumnWidth

Indicates how wide each column should be in a multicolumn checked list box

Cursor

The cursor that appears when the mouse passes over the checked list box

DataSource

Indicates the list that the checked list box will use to get its items

DisplayMember

Indicates the property to display for the items in the checked list box

Font

The font used to display text in the checked list box

ForeColor

The foreground color used to display text and graphics in the checked list box

HorizontalExtent

The width, in pixels, by which a list box can be scrolled horizontally (Only valid if HorizontalScrollBar is True)

HorizontalScrollbar

Indicates whether the checked list box will display a horizontal scrollbar for items beyond the right edge of the checked list box

IntegralHeight

Indicates whether the list can contain only complete items

Items

The items in the checked list box

MultiColumn

Indicates if values should be displayed in columns horizontally

RightToLeft

Indicates whether the control should draw right-to-left for RTL languages

ScrollAlwaysVisible

Indicates if the checked list box should always have a scrollbar present, regardless of how many items are in it

SelectionMode

Indicates if the checked list box is to be single-select, multiselect, or unselectable

Sorted

Controls whether the checked list box is sorted

TabIndex

Determines the index in the tab order that the checked list box will occupy

TabStop

Indicates whether the user can use the tab key to give focus to the control

ThreeDCheckBoxes

Indicates whether the check values should be shown as flat or 3D check marks

UseTabStops

Indicates if tab characters should be expanded into full spacing

ValueMember

Indicates the property to use as the actual value for the items in the checked list box

You can change the appearance of the check boxes that appear next to the items by using the ThreeDCheckBoxes property. The check boxes can appear as flat or 3D check marks. The CheckOnClick property determines if the items are toggled with the first click of an item. To toggle items with the first click, set the CheckOnClick property to True.

You can quickly add multiple items to a checked list box. Adding multiple items to a checked list box is a multistep process. To add items to a checked list box:

1.   Create an array of type System.Object.

2.   Set each member of the array to a string—the string becomes the text displayed in the list.

3.   Set the Items collection's All property to the array.

For example, suppose you want to display the days of the week in a checked list box. Follow the steps just outlined in the manner shown next:

'Create an array of type System.Object

Dim objDaysOfTheWeek(7) As System.Object

       

'Set each member of the array to a string

objDaysOfTheWeek(0) = "Monday"

objDaysOfTheWeek(1) = "Tuesday"

objDaysOfTheWeek(2) = "Wednesday"

objDaysOfTheWeek(3) = "Thursday"

objDaysOfTheWeek(4) = "Friday"

objDaysOfTheWeek(5) = "Saturday"

objDaysOfTheWeek(6) = "Sunday"

 

'Set the Items collection's All property to the array

clbDaysOfTheWeek.Items.All = objDaysOfTheWeek

 

Goto Page 2 >>
  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy