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.

ListView Control

The ListView control can display text in four different views: text-only, text-with-small-icons, text-with-large-icons, or report. A list view is similar to the right pane that displays the contents of the selected folder in Windows Explorer. Just as you can use the View menu in Windows Explorer to change how the icons in the right pane appear, you can change how items in a list view appear.

The list view comes in handy when you want to display items that contain multiple pieces of information, because it can show more than one column. For example, you can use a list view on an About box to display version information of key files used by your application. Your list view would have three columns with the headings “File,” “Version,” and “Full Path.” All the information you need to support your user would be readily available. We will look at code snippets that allow you to create a version information box. Table 8.13 shows the properties of the ListView control.

Table 8.13 ListView Properties

Property

Description

Activation

Indicates the type of action required by the user to activate an item, and the feedback given

Alignment

Indicates how items are aligned within the list view

AllowColumnReorder

Indicates whether the user can reorder columns in the Report view

AllowDrop

Determines if the list view will receive drag-drop notifications

AutoArrange

Indicates whether items are kept arranged automatically

BackColor

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

BorderStyle

The border style of the list view

CheckBoxes

Indicates whether check boxes are displayed beside items

Columns

The columns shown in Report view

Cursor

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

Font

The font used to display text in the list view

ForeColor

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

FullRowSelect

Indicates whether all subitems are highlighted along with the item when selected

GridLines

Displays grid lines around items and subitems

HeaderStyle

The style of the column headers in Report view

HideSelection

Removes highlighting from the selected item when the list view loses focus

HoverSelection

Allows items to be selected by hovering over them with the mouse

LabelEdit

Allows item labels to be edited in place by the user

LabelWrap

Determines whether label text can wrap to a new line

LargeImageList

The image list used by the list view for images in Large Icon view

ListItems

The items in the list view

MultiSelect

Allows multiple items to be selected

RightToLeft

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

Scrollable

Indicates whether the list view will display scrollbars if it contains more items than can fit in the client area

SmallImageList

The image list used by the list view for images in all views except for the Large Icon view

Sorting

Indicates the manner in which items are to be sorted

StateImageList

The image list used by the list view for custom states

TabIndex

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

TabStop

Indicates whether the user can use the tab key to give focus to the list view

View

Selects one of four different views in which items can be shown

The View property is an important property of the list view, because it determines one of four different views in which items can be shown: text-only, text-with-small-icons, text-with-large-icons, or report. The self-explanatory text-only view renders items in much the same manner as a list box. The text-with-small-icons, text-with-large-icons, and report views are similar to the Small Icons, Large Icons, and Detail views in Windows Explorer.

The ListItems property holds the items in a list view. If a ListView control has multiple columns, the items have subitems that hold information in the columns beyond the first. For example, a list view with one row and three columns has one item (to hold the information in the first column) and two subitems (to hold the information in the second and third columns).

Another useful property of the list view is the HeaderStyle property. The HeaderStyle property determines the style of the column headers in Report view. The property can be set to show no headers, clickable headers, and non-clickable headers.

Before we delve into our example, you should be familiar with the Sorting property of the list view. The Sorting property indicates the manner in which items are to be sorted. Items can remain unsorted, or you can sort them by ascending or descending order.

Let’s create our version information box. Our box will have three columns to show a file’s name, its version, and its full path. Declare three variables to hold these values:

Dim strFile As String

Dim strVersion As String

Dim strFullPath As String

Declare an array of strings to hold subitems in the list view. The array has size two to show two columns in addition to the first in the list view.

Dim strSubItems(2) As String

Our ListView control will show information about the common control DLL comctl32.dll. The following statement assigns the appropriate values to the variables we declared:

'Set the file's name, version, and full path

strFile = "comctl32.dll"

strVersion = "5.81"

strFullPath = "C:\WINNT\system32\COMCTL32.DLL"

We now need to fill our subitem array with the file’s version and full path. These will be displayed in the second and third columns of the list view.

'Fill the subitem array

strSubItems(0) = strVersion

strSubItems(1) = strFullPath

We are now ready to set properties of the list view. We want to display the items in Report view, have clickable headers, and display items in ascending order.

With lvwVersionInformation

   .View = View.report

   .HeaderStyle = ColumnHeaderStyle.Clickable

   .Sorting = SortOrder.Ascending

The following statements add three columns to the list view. The column headings are “File,” “Version,” and “Full Path,” and the column widths are 100, 100, and 200. The text in all columns aligns with the left margin.

   .Columns.Add("File", 100, HorizontalAlignment.Left)

   .Columns.Add("Version", 100, HorizontalAlignment.Left)

   .Columns.Add("Full Path", 200, HorizontalAlignment.Left)

To add the item to the list view, use the Add method of the Columns property. The first parameter is the name of the file, the second is the index of an appropriate image, and the third is the array of subitems:

   .ListItems.Add(strFile, 0, strSubItems)

End With

The list view now shows the version information of the common control DLL. The following is the full code listing for the example:

Dim strFile As String

Dim strVersion As String

Dim strFullPath As String

Dim strSubItems(2) As String

       

'Set the file's name, version, and full path

strFile = "comctl32.dll"

strVersion = "5.81"

strFullPath = "C:\WINNT\system32\COMCTL32.DLL"

       

'Fill the subitem array

strSubItems(0) = strVersion

strSubItems(1) = strFullPath

       

With lvwVersionInformation

    'Set the view to Report view

    .View = View.report

 

    'Set the header style to clickable          

    .HeaderStyle = ColumnHeaderStyle.Clickable

           

    'Display items in ascending order

    .Sorting = SortOrder.Ascending

 

    'Add File, Version, and Full Path columns

    .Columns.Add("File", 100, HorizontalAlignment.Left)

    .Columns.Add("Version", 100, HorizontalAlignment.Left)

    .Columns.Add("Full Path", 200, HorizontalAlignment.Left)

 

    'Add item

    .ListItems.Add(strFile, 0, strSubItems)

End With

ComboBox Control

The Windows Forms ComboBox control displays a list from which the user can select one or more choices. The ComboBox control appears as a text box and an associated list box. As text is typed into the text box, the list scrolls to the nearest match. In addition, when the user selects an item in the list box, it automatically uses that entry to replace the content of the text box and selects the text.

Because a combo box is similar to a list box, you may wonder when to use one or the other, but there are differences. Unlike a list box, a combo box allows the user to type an item that does not appear in the list. In general, use a combo box to present to the user a list of merely suggested choices, and use a list box to strictly limit the user’s input to only the choices you present. In addition, as a combo box generally consumes less space on a form than a list box, a combo box may be a better choice when such space is at a premium.

The combo box has three different styles: simple, drop down, and drop-down list. In the simple style, the combo box has an edit box along with a list box. In the drop down style, the combo box looks like an edit box, but you can click it to see a drop down containing its items. The drop-down list style is similar to the drop down style. However, in the drop down list style, the user can only choose an item in the list. No item can be entered that does not appear in the list. Table 8.14 shows the properties of the ComboBox control.

 

Table 8.14 ComboBox Properties

Property

Description

AllowDrop

Determines if the combo box will receive drag-drop notifications

BackColor

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

Cursor

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

DataSource

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

DisplayMember

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

Font

The font used to display text in the combo box

ForeColor

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

IntegralHeight

Indicates whether the list portion can contain only complete items

ItemHeight

The height, in pixels, of items in an owner-drawn combo box

Items

The items in the combo box

MaxDropDownItems

The maximum number of entries to display in the drop-down list

MaxLength

Specifies the maximum number of characters that can be entered into the combo box

RightToLeft

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

Sorted

Controls whether items in the list portion are sorted

Style

Controls the appearance and functionality of the combo box

TabIndex

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

TabStop

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

Text

The text contained in the combo box

ValueMember

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

 

You can add items to the combo box at design-time. To add items to a combo box at design-time:

1.   Select the ComboBox control on the form.

2.   If necessary, use the View menu to open the Properties window.

3.   In the Properties window, click the Items property, then click the ellipsis.

4.   In String Collection Editor, type the first item, then press Enter.

5.   Type the next items, pressing Enter after each item.

6.   Click OK.

There are a variety of ways to programmatically add items to a combo box. You can simply add an item to the list, letting the combo box control the position of insertion based on whether or not it is sorted. Alternatively, you can make explicit the point at which to insert an item. To simply add an item to a combo box, use the Add method of the Items collection:

'Add an item

cboUser.Items.Add("(New User)")

To add an item to a combo box, specifying the point of insertion, use the Insert method of the Items collection. This is useful when you want to specifically insert an item at a particular spot. This does not work when the Sorted property is set to True. As with other index properties, the point of insertion is zero-based; in the example that follows, the item is added at the first position in the list:

'Add an item at the first position

cboUser.Items.Insert(0, "(New User)")

Now, let's look at removing an item. You can remove an item by its index or by its value. For instance, to remove the first item in a list (by specifying its zero-based position), use the Remove method of the Items collection as follows:

'Remove the first item

cboUser.Items.Remove(0)

You can also remove an item by its value. Here is a snippet that specifies the value of the item to be removed:

'Remove the item "(New User)"

cboUser.Items.Remove("(New User)")

Sometimes you want to remove the selected item. You can use the SelectedItem and Remove methods for this. Let's look at how this is done in code:

'Remove the selected item

cboUser.Items.Remove(cboUser.SelectedItem)

DomainUpDown Control

The DomainUpDown control displays a list from which the user can select only one choice. You can use a combo box for everything you can use a domain up-down control for. However, a domain up-down control is generally used when the items have an inherent order, like days of the week, or months of the year.

The Domain UpDown control consists of an edit box and up-down buttons. The edit box displays the currently selected item. The user can select the next or previous item in the list by clicking the up-down buttons or pressing the Up Arrow and Down Arrow keys. Table 8.15 shows the properties of the DomainUpDown control.

Table 8.15 DomainUpDown Properties

Property

Description

AllowDrop

Determines if the up-down control will receive drag-drop notifications

BackColor

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

BorderStyle

Indicates the border style of the up-down control

Cursor

The cursor that appears when the mouse passes over the up-down control

Font

The font used to display text in the up-down control

ForeColor

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

InterceptArrowKeys

Indicates whether the up-down control will increment and decrement the value when the up arrow and down arrow keys are pressed

Items

The allowable values of the up-down control

ReadOnly

Indicates whether or not the up-down control is read-only

RightToLeft

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

Sorted

Controls whether items in the domain list are sorted

TabIndex

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

TabStop

Indicates whether the user can use the tabkey to give focus to the up-down control

Text

The text contained in the up-down control

TextAlign

Indicates how the text should be aligned in the edit box

UpDownAlign

Indicates how the up-down control will position the up-down buttons relative to its edit box

Wrap

Indicates whether or not values wrap around at either end of the item list

The Text property holds the text contained in the up-down control. Another important property is the Items collection, which holds the items in the up-down control. You can use the Items property to programmatically add items to, and remove items from, the up-down control. We have added items to and removed items from many of the controls we discussed previously. However, you will often want to add items to an up-down control at design-time. To add items to an up-down control on a form at design-time:

1.   Click the DomainUpDown control on the form.

2.   In the Properties window, click the Items property, then click the ellipsis.

3.   In the String Collection Editor window, type the first item, then press Enter.

4.   Type the next items, pressing Enter after each item.

5.   Click OK.

When the ReadOnly property is set to True, the Items property holds the only allowable values of the up-down control. In other words, the Items property is the domain of a read-only up-down control, which is where the control gets its name. The user cannot type a new value in a read-only up-down control. Instead, a keystroke selects the item in the control that starts with the letter pressed.

You can change the horizontal alignment of the up-down buttons. The default alignment of the up-down buttons is with the right margin of the control. To align the up-down buttons to the left of the edit box, set the UpDownAlign property as follows:

'Align the up-down buttons to the left of the edit box       

dudDaysOfTheWeek.UpDownAlign = LeftRightAlignment.Left

The DomainUpDown control  is similar to another control, the NumericUpDown control. In the next section, we will take a closer look at the numeric up-down control.

NumericUpDown Control

The NumericUpDown control allows the user to quickly change a numeric value by a chosen increment. The numeric up-down control shares many properties with the domain up-down control, but it is used to display numbers instead of text. The numeric up-down control is a great choice when collecting input such as a number of employees and a number of days from the user. Table 8.16 shows the properties of the NumericUpDown control:

 

Table 8.16 NumericUpDown Properties

Property

Description

AllowDrop

Determines if the up-down control will receive drag-drop notifications

BackColor

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

BorderStyle

Indicates the border style of the up-down control

Cursor

The cursor that appears when the mouse passes over the up-down control

DecimalPlaces

Indicates the number of decimal places to display

Font

The font used to display text in the up-down control

ForeColor

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

Hexadecimal

Indicates whether the up-down control should display its value in hexadecimal

Increment

Indicates the amount to increment/decrement on each button click

InterceptArrowKeys

Indicates whether the up-down control will increment and decrement the value when the up arrow and down arrow keys are pressed

Maximum

Indicates the maximum value for the up-down control

Minimum

Indicates the minimum value for the up-down control

ReadOnly

Indicates whether or not the edit box is read-only

RightToLeft

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

TabIndex

Determines the index in the tab order that the up-down control will occupy

TabStop

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

TextAlign

Indicates how the text should be aligned in the edit box

ThousandsSeparator

Indicates whether thousands separators will be inserted between every three digits

UpDownAlign

Indicates how the up-down control will position the up-down buttons relative to its edit box

Value

The current value of the up-down control

The numeric up-down control has several unique properties. The Value property holds the current value of the numeric up-down control. The user can use the up-down buttons to increment or decrement the current value by the value of the Increment property.

The default value of the Increment property is 1. You can set the Increment property to a smaller value and display decimal places by increasing the value of the DecimalPlaces property. Along with displaying decimal places, you can also display thousands separators between every three digits.

The Minimum and Maximum properties indicate the minimum and maximum values of the up-down control. The value of the up-down control cannot be decremented past the value of the Minimum property. Also, the current value cannot be incremented past the value of the Maximum property.

PictureBox Control

The Windows Forms PictureBox control is used to display images in bitmap, GIF, icon, or JPEG formats. For example, you can use a picture box to display the logo of your company in the About box of your application. You can also change the image displayed in a picture box at runtime. Table 8.17 contains the properties of the PictureBox control.

Table 8.17 PictureBox Properties

Property

Description

BackColor

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

BackgroundImage

The background image used for the control

BorderStyle

Controls what type of border the picture box should have

Cursor

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

Image

The image displayed in the picture box

SizeMode

Controls how the picture box will handle image placement and control sizing

TabIndex

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

You can programmatically change the image displayed in a picture box, which is particularly useful when you use a single form to display different pieces of information. For instance, you may choose to create one dialog box to display errors or status at different times during the run, and display different images for different messages. To set a picture at runtime, use the FromFile method of the Image class as follows:

'Display the company logo

Dim strImagePath As String = "Company Logo.jpg"

picCompanyLogo.Image = Image.FromFile(strImagePath)

You can also set a picture at design-time. To set a picture at design-time:

1.   Select the picture box on the form.

2.   If necessary, use the View menu to open the Properties window.

3.   Select the Image property. Choose the picture in the Open File dialog box.

If you use a picture box to display images of different sizes, use the SizeMode property to size the picture box to prevent image cropping. You can set the SizeMode property to the following values:

·     PictureBoxSizeMode.AutoSize to automatically resize the picture box

·     PictureBoxSizeMode.CenterImage to center the image in the picture box

·     PictureBoxSizeMode.Normal for not resizing either the image or the picture box

·     PictureBoxSizeMode.StretchImage to stretch the image to the size of the fixed picture box

You can allow the picture box to automatically resize as follows:

'Allow the picture box to automatically resize

picCompanyLogo.SizeMode = PictureBoxSizeMode.AutoSize

At times you may want to clear the picture box and remove the image. To clear a picture box, simply set its Image property to Nothing. Here is what it would like in code:

'Clear the picture box

picCompanyLogo.Image = Nothing

TrackBar Control

The Windows Forms TrackBar control is a control similar to the ScrollBar that allows the user to scroll through a range of values. The track bar is great for adjusting volume, contrast, and brightness levels. It consists of a slider and tick marks. The user can adjust the value of the track bar by dragging the slider, using the arrow keys, or using the Page Up or Page Down keys. Table 8.18 shows the properties of the TrackBar control.

Table 8.18 TrackBar Properties

Property

Description

AllowDrop

Determines if the track bar will receive drag-drop notifications

AutoSize

Indicates whether the track bar will resize itself automatically based on a computation of the default scrollbar dimensions

BackColor

The background color used to display text and graphics in the track bar

Cursor

The cursor that appears when the mouse passes over the track bar

LargeChange

The number of positions the slider moves in response to mouse clicks or the Page Up and Page Down keys

Maximum

The maximum value for the position of the slider on the track bar

Minimum

The minimum value for the position of the slider on the track bar

Orientation

The orientation of the track bar

RightToLeft

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

SmallChange

The number of positions the slider moves in response to keyboard input (arrow keys)

TabIndex

Determines the index in the tab order that the track bar will occupy

TabStop

Indicates whether the user can use the Tab key to give focus to the track bar

TickFrequency

The number of positions between tick marks

TickStyle

Indicates where the ticks appear on the track bar

Value

The position of the slider

The track bar shares most of its properties with other controls. You should be familiar with the Value property, which indicates the position of the slider. You should also know about the SmallChange and LargeChange properties. The SmallChange property determines the number of positions the slider moves to the right when the user uses the Right Arrow and Down Arrowkeys, and to the left when the user uses the Left Arrow and Up Arrow keys. The LargeChange property determines the number of positions the slider moves in response to mouse clicks or when the Page Up and Page Down keys are pressed. The LargeChange property also determines the number of positions the slider moves when the user clicks to the left or right of the slider.

The Maximum and Minimum properties determine the maximum and minimum values for the position of the slider on the track bar. The TickFrequency property holds the number of positions between tick marks.

As for appearance, the TickStyle property indicates where the ticks appear on the track bar, which can be at the bottom right or top left of the slider, at both sides, or not at all. For example, to make the tick marks appear on both sides of the slider, use the TickStyle property as follows:

'Show tick marks at both sides of the slider

trkVolume.TickStyle = TickStyle.Both

Next, we will look at a powerful control: the DateTimePicker control.

DateTimePicker Control

The Windows Forms DateTimePicker control allows you to display and collect dates and times for the user. The date-time picker is a great replacement for a masked edit control with a date-time mask, because it allows you to display calendar information as you collect input from the user. For example, the date-time picker allows the user to view the days of the week around the day selected, or to view different months, as if flipping through a calendar. Another advantage of the date-time picker is that it disallows invalid input. While you can quickly set up a masked edit control to disallow alpha characters in a numeric field, it requires coding to disallow other invalid input such as 13 in a month field.

The date-time picker consists of a text box with an accompanying calendar drop down. The user can input a date in several ways. First, the user can enter a date by simply typing it into the text box. As discussed before, the date-time picker validates the entry and disallows it if it is invalid. Second, the user can use the drop down to navigate to a date. Third, the user can use the drop down and quickly click on Today’s Date to enter the current date, regardless of the month displayed in the drop down.

The date-time picker can also show only time. The date-time picker shows only time when the Format property is set to Time. In that case, the date-time picker does not show a drop-down calendar, but you can still use it to collect only times that are valid.

The most important property of the date-time picker is the Value property, which holds the selected date and time. The Value property is set to the current date by default. To change the date before displaying the control, use the Value property as follows:

'Change the date to the following day

dtpEffectiveDate.Value = _

    DateAdd(Microsoft.VisualBasic.DateInterval.Day, 1, Date.Today)

Table 8.19 shows the other properties of the DateTimePicker control.

Table 8.19 DateTimePicker Properties

Property

Description

AllowDrop

Determines if the date-time picker will receive drag-drop notifications

CalendarFont

The font used to display the calendar

CalendarForeColor

The color used to display text within a month

CalendarMonthBackground

The background color displayed within the month

CalendarTitleBackColor

The background color displayed in the calendar’s title

CalendarTitleForeColor

The color used to display text within the calendar’s title

CalendarTrailingForeColor

The color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar

Cursor

The cursor that appears when the mouse passes over the control

CustomFormat

The custom format string used to format the date or time displayed in the date-time picker

DropDownAlign

Controls whether the month drop down is aligned to the left or right of the date-time picker

Font

The font used to display text in the date-time picker

Format

Determines whether dates and times are displayed using standard or custom formatting

MaxDate

The maximum date selectable

MinDate

The minimum date selectable

ReadOnly

Determines whether the user can free-form edit the date field. If this is set to False, then onUserString events will be fired

RightToLeft

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

ShowCheckBox

Determines whether a check box is displayed in the date-time picker. When the check box is unchecked, no value is selected

ShowUpDown

Controls whether an up-down button is used to modify dates instead of a drop-down calendar

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 date-time picker

Value

The current date/time value for the date-time picker

ValueSet

Determines if the None check box is checked, indicating the user has selected a value

The CheckBox property is another key property of the date-time picker. Ordinarily, the CheckBox property is set to False and the date-time picker always holds a value. There may be times, however, when you want to allow the user not to specify a value—for example, if you are using a date-time picker to collect an employee’s date of termination, but the employee is still active. In such a case, set the CheckBox property to True as follows:

dtpDateOfTermination.CheckBox = True

When the CheckBox property is set to True, the edit portion of the date-time picker displays a check box. Your user can now uncheck the box to indicate that there has not been a date of termination. When an employee is terminated, the user can check the box, and select the appropriate date. It is important to note that when the check box is unchecked, the date-time picker Value property returns Null.

You should be familiar with another property of the date-time picker, the Format property. The Format property allows you to use standard formatting strings or custom formats to display the date. To display a custom format, use the Format property along with the CustomFormat property as follows:

'Display the day of week

dtpDayOfWeek.Format = _

    System.WinForms.DateTimePickerFormats.Custom dtpDayOfWeek.CustomFormat = "dddd"

You should also be familiar with the MinDate and MaxDate properties. The MinDate property is the minimum date selectable and the MaxDate is the maximum date selectable. The user cannot choose a date before the minimum date. This is useful when you need to compare dates. For example, you would not want the user to enter a date of termination that occurs before the date of hire.

Panel Control

The Windows Forms Panel control is used to group other controls. A panel allows you to give the user a logical visual cue of controls that belong together. For example, on a dialog box that displays properties of a file, you could place all check boxes describing the attributes of the file—Archive, Normal, System, Hidden, and ReadOnly—on one panel to help the user identify them as one group. In addition, a panel is also useful at design-time, as you can move all controls on a panel simultaneously by moving only the panel. Table 8.20 shows the properties of the Panel control.

Table 8.20 Panel Properties

Property

Description

AllowDrop

Determines if the panel will receive drag-drop notifications

AutoScroll

Determines whether scroll bars will automatically appear if controls are placed outside the form’s client area

AutoScrollMargin

The margin around controls during autoscrolls

AutoScrollMinSize

The minimum logical size for the autoscroll region

BackColor

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

BackgroundImage

The background image used for the panel

BorderStyle

Indicates whether or not the panel should have a border

Cursor

The cursor that appears when the mouse passes over the panel

DockPadding

Determines the size of the border for docked controls

DrawGrid

Indicates whether or not to draw the positioning grid

Font

The font used to display text in the panel

ForeColor

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

GridSize

Determines the size of the positioning grid

RightToLeft

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

SnapToGrid

Determines if controls should snap to the positioning grid

TabIndex

Determines the index in the  order that the panel will occupy

TabStop

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

Let's look at how you can add check boxes to a panel in code. The following snippet adds check boxes describing file attributes to a panel:

'Add file attribute checkboxes to a panel

With pnlAttributes.Controls

    .Add(chkArchive)

    .Add(chkNormal)

    .Add(chkSystem)

    .Add(chkHidden)

    .Add(chkReadOnly)

End With

The BorderStyle property indicates whether a panel should have a border. You can add a 3D border or a flat border to a panel. Your panel can also have no border. Let's look at the code for these options:

pnlAttributes.BorderStyle = WinForms.BorderStyle.Fixed3D

pnlAttributes.BorderStyle = WinForms.BorderStyle.FixedSingle

pnlAttributes.BorderStyle = WinForms.BorderStyle.None

You can change the background color used to display graphics and text in a panel. When you change a panel’s background color, the background color of all the controls it contains also changes to the color you set.

'Change background color to gray

panel1.BackColor = Color.Gray

Your panel can also display a background image, which appears behind the controls contained within the panel. To display a background image, set the BackgroundImage property as follows:

pnlAttributes.BackgroundImage = Image.FromFile("Background.jpg")

GroupBox Control

Like the Panel Control, the GroupBox control is used to group other controls. In contrast to the Panel control, the GroupBox cannot have scrollbars and only the GroupBox allows you to display a caption with a group of controls. This is similar to the Frame control in previous versions of Visual Basic. Nonetheless, you can use the Add method we discussed in the previous section to create a group of controls. The group box also allows you to set the background programmatically using the BackColor and BackgroundImage properties discussed in the previous section. Table 8.21 shows the other properties of the GroupBox control.

Table 8.21 GroupBox Properties

Property

Description

BackColor

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

BackgroundImage

The background image used for the control

DrawGrid

Indicates whether or not to draw the positioning grid

Font

The font used to display text in the group box

ForeColor

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

GridSize

Determines the size of the positioning grid

RightToLeft

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

SnapToGrid

Determines if controls should snap to the positioning grid

TabIndex

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

Text

The text contained in the group box

TabControl Control

The Windows Forms TabControl control is used to hold controls separated by tabs. The tab control is handy when you need to display different groups of information on limited real estate. You can put each group of information on a separate tab of the tab control. For example, in a payroll application you can put an employee's general information, such as her name and address, on one tab and information about her dependents on another tab.

The TabPages property is an important property of the tab control, because it controls the collection of tab pages. Often, you will want to add tab pages to a tab control at design-time so you can add controls to each page. To add a tab page to a tab control:

1.   Select the tab control on the form.

2.   If necessary, use the View menu to open the Properties window.

3.   Click the TabPages property, then click the ellipsis.

4.   In Tab Page Collection Editor, click Add.

5.   In the TabPage1 Properties box, change the Text property to an appropriate caption for the tab page.

6.   Click OK.

The tab control has other unique properties. Table 8.22 lists the properties of the TabControl control.

Table 8.22 TabControl Properties

Property

Description

Alignment

Determines whether the tabs appear on the top, bottom, left, or right side of the tab control (left or right are implicitly multilined)

AllowDrop

Determines if the tab control will receive drag-drop notifications

Appearance

Indicates whether the tabs are painted as buttons or regular tabs

Cursor

The cursor that appears when the mouse passes over the tab control

DrawGrid

Indicates whether or not to draw the positioning grid

DrawMode

Indicates whether the user or the system paints the captions

Font

The font used to display text in the tab control

GridSize

Determines the size of the positioning grid

HotTrack

Indicates whether the tabs visually change when the mouse passes over them

ImageList

The image list from which the tab control takes its images

ItemSize

Determines the width of fixed-width or owner-draw tabs and the height of all tabs

Locked

Determines if the user can move or resize the control

MultiLine

Indicates if more than one row of tabs is allowed

Padding

Indicates how much extra space should be added around the text/image in the tab, if the DrawMode property value is Fixed

RightToLeft

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

ShowToolTips

Indicates whether tooltips should be shown for tables that have their tooltips set

SizeMode

Indicates how tabs are sized

SnapToGrid

Determines if controls should snap to the positioning grid

TabIndex

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

TabPages

The tab pages in the tab control

TabStop

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

Another property you should be familiar with is the MultiLine property. The MultiLine property determines if more than one row of tabs is allowed. This property is useful when you have a large number of tabs or long captions. You can ensure the captions are visible by setting the MultiLine property to True.

The HotTrack property is an eye-catching, commonly used property of the tab control. When the HotTrack property is set to True, the caption of the tabs change colors when the mouse passes over them. The tabs change to their regular color when the mouse is not over them.

We have now discussed the powerful controls built into Visual Basic .NET. However, at times these controls will not quite provide the functionality you want. When that happens, you will want to create your own controls. Next, we will look at creating custom Windows components and controls.

Creating Custom Windows Components

The Windows Forms framework offers numerous components that you can use to build applications. In advanced applications these components may not provide the functionality you want. Should this be the case, you can create your own components to provide exactly what you need. But what exactly are components?

A component is a class with emphasis on cleanup and containment. Components provide reusable code in the form of objects. You can think of a component as a control without user interface capabilities. Therefore, it makes sense to discuss how to author a component before we look at authoring controls. The two are very similar, and you can use everything you know about authoring a component when you author a control.

A good way to understand how to author a component is by walking through the process. In the following exercise you will create a component.

Exercise 8.1: Creating a Custom Windows Component

In this exercise, you will create a class library project for a component CFirst, add constructors and destructors, add a property, and test the component. It is useful to have the Toolbox, Solution Explorer, Properties, and Task List windows open when you start creating your component:

1.   Use the View menu to open the Toolbox, Solution Explorer, and the Properties window.

2.   From the View menu, point to Other Windows and then select Task List to open the Task List.

 

Creating a Class Library Project

To create a component, you have to create a class library. Visual Basic .NET provides you with a class library project template to help you create the class library. To create the CFirstLib class library and the CFirst component:

1.   On the File menu, select New and then Project to open the New Project dialog box. From the list of Visual Basic Projects, select the Class Library project template, and enter CFirstLib in the Name box.

Note

When you create a new project, always specify its name to set the root namespace, assembly name, and project name. Doing so also ensures that the default component will be in the correct namespace.

2.   In Solution Explorer, right-click Class1.vb and select View Code from the shortcut menu.

3.   In the Code window, locate the Class statement, Public Class Class1, and change the name of the component from Class1 to CFirst.

Note

As shown by the Inherits statement immediately below the Class statement, a component inherits from the Component class by default. The Component class provides the ability to use designers with your component.

4.   In Solution Explorer, click Class1.vb, and in the Properties window change the filename to CFirst.vb.

5.   On the File menu, select Save CFirst.vb to save the project.

Adding Constructors and Destructors

We now add constructors and destructors to control the way the CFirst component is initialized and torn down. The only function of our component will be to maintain a running count of how many CFirst objects are in memory at any given time. When a CFirst object is initialized, the running count will be incremented, and when it a CFirst object is torn down, the running count will be decremented. To add code for the constructor and destructor of the CFirst class:

1.   In the Code Editor window (either before or after the declaration of the components container) add member variables to keep a running total of instances of the CFirst class, and an ID number for each instance:

Public ReadOnly intInstanceID As Integer

Private Shared intNextInstanceID As Integer = 0

Private Shared intClassInstanceCount As Integer = 0

Shared member variables such as intClassInstanceCount and intNextInstanceID are initialized the first time the CFirst class is referred to in code and exist at the class level only. All instances of CFirst that access these members will use the same memory locations. Read-only members such as intInstanceID can be set only in the constructor:

2.   Locate Public Sub New, the default constructor for the CFirst class. After the call to InitializeComponent, add the following code to set the instance ID number and to increment the instance count when a new CFirst object is created:

intInstanceID = intNextInstanceID

intNextInstanceID += 1

intClassInstanceCount += 1

3.   Add the following method after the end of the constructor to decrement the instance count just before the CFirst object is removed from memory:

Protected Overrides Sub Finalize()

    intClassInstanceCount -= 1

End Sub

 

Adding a Property to the Class

Now we will add a single property to our CFirst class. The shared property intClassInstanceCount holds the number of CFirst objects in memory. To create a property for the CFirst class:

·     Add the following property declaration to the CFirst class.

Public Shared ReadOnly Property InstanceCount() As Integer

    Get

        Return intClassInstanceCount

    End Get

End Property

Testing the Component

To test our CFirst component, we need to create a client project that uses the component. In order to do this, we need to set the client project as the startup project to ensure it will be the first to run when our solution is started. We will call the client project CFirstTest. To add the CFirstTest client project as the startup project for the solution:

1.   On the File menu, select Add Project and then New Project to open the Add New Project dialog box.

2.   From the list of Visual Basic Projects, select the Windows Application project template. In the Name box, type CFirstTest, then click OK.

3.   In Solution Explorer, right-click CFirstTest and click Set As Startup Project on the shortcut menu.

In order to use the fully qualified name of the CFirst component (CFirstLib.CFirst), we need to add a reference to the class library project.

To add a reference to the class library project:

1.   In Solution Explorer, right-click the References node immediately beneath CFirstTest, and select Add Reference from the shortcut menu.

2.   In the Add Reference dialog box, select the Projects tab.

3.   Double-click the CFirstLib class library project to add it to the Selected Components list. CFirstLib will appear under the References node for the CFirstTest project. Click OK.

4.   In Solution Explorer, right-click Form1.vb and select View Code from the shortcut menu.

Adding an Imports statement allows us to refer to the component type as CFirst, omitting the library name. This makes it easier to use the component. To add an Imports statement:

·     Add the following Imports statement to the list of Imports statements at the top of the Code Editor window for Form1.

Imports CFirstLib

Using the Component

You can now use the component’s properties in code. We need to add a button to our form to create new instances of CFirst. To use the CFirst component programmatically:

1.   From the Toolbox window, select the Win Forms tab, and double-click the Button control.

2.   On Form1, double-click the Button control. In the Click event handler for Button1, add the following code:

Dim objCFirst As New CFirst()

       

MessageBox.Show("There are " & objCFirst.InstanceCount _

    & " CFirst objects in memory.")

As yo u type the code in the Code window, the Complete Word box will appear displaying the InstanceCount property. You can expose methods similarly.

Creating Custom Windows Controls

As we discussed, controls are components with user interface capabilities. There is a lot of overlap between component creation and control creation. Instead of discussing the similarities, let's look at a common problem. You have a certain built-in control available to you and you are happy with it, except for this one nagging feature. The control does not do exactly what you want, or it lacks one feature you need. You will find that often you do not need a whole new control; you just need to be able to change an existing one.

This can be done by inheriting from a control. For a simple example, let's look at a Button control. You can create your own control to be placed in the Toolbox window. To keep it simple, let's say you want to create a custom control that inherits from the Button control but has a different background color. This is a small change, but once we discuss how to make this small change, you can change other controls to do more elegant things.

Exercise 8.2: Creating a Custom Windows Control

In this exercise, you will create a custom control that inherits from the Windows Forms Button. Our custom control will resemble the Windows Forms Button control, but our custom control will have a white background. It is useful to have the Toolbox, Solution Explorer, Properties, and Task List windows open when you start creating your component:

1.   Use the View menu to open the Toolbox, Solution Explorer, and the Properties window.

2.   From the View menu, point to Other Windows and then select Task List to open the Task List.

Creating a Control Library Project

As with components, we need to create a control library. Visual Basic .NET provides you with a control library project template to help you create the control library.

To create the CMyButtonLib class library and the CMyButton component:

1.   On the File menu, select New and then Project to open the New Project dialog box. From the list of Visual Basic Projects, select the Windows Control Library project template, and enter CMyButtonLib in the Name box.

2.   In Solution Explorer, right-click Control1.vb and select View Code from the shortcut menu.

3.   In the Code window, locate the Class statement, Public Class Control1, and change the name of the component from Control1 to CMyButton.

4.   In Solution Explorer, click Control1.vb and in the Properties window change the filename to CMyButton.vb.

5.   On the File menu, select Save CMyButton.vb to save the project.

Adding Constructors and Destructors

We now add constructors and destructors to control the way the CMyButton control is initialized and torn down. Our component will resemble a button control, but our component’s background color will be white. To add code for the constructor and destructor of the CMyButton control:

·     Locate Public Sub New, the default constructor for the CMyButton class. After the call to InitializeComponent, add the following code to set the background color to white.

Me.BackColor = System.Drawing.Color.White

Testing the Component

To test our CMyButton control, we need to create a client project that uses the control.

1.   On the File menu, select Add Project and then New Project to open the Add New Project dialog box.

2.   From the list of Visual Basic Projects, select the Windows Application project template. In the Name box, type CmyButtonTest, then click OK.

3.   In Solution Explorer, right-click CMyButtonTest and click Set As Startup Project on the shortcut menu.

In order to use the fully qualified name of the CButton control (CMyButtonLib.CMyButton), we need to add a reference to the control library project.

To add a reference to the control library project:

1.   In Solution Explorer, right-click the References node immediately beneath CMyButtonTest, and select Add Reference from the shortcut menu.

2.   In the Add Reference dialog box, select the Projects tab.

3.   Double-click the CMyButton class library project to add it to the Selected Components list. CMyButton will appear under the References node for the CMyButtonTest project. Click OK.

4.   In Solution Explorer, right-click Form1.vb and select View Code from the shortcut menu.

Adding an Imports statement allows us to refer to the component type as CFirst, omitting the library name. This makes it easier to use the component.

To add an Imports statement,

·     Add the following Imports statement to the list of Imports statements at the top of the Code Editor window for Form1.

Imports CMyButtonLib

Using the Component

You can now use the component’s properties in code. We need to add a button to our form to create new instances of CFirst. To use the CFirst component programmatically:

·     Double-click Form1. In the Click event handler, add the following code:

Dim btnMyButton As New CMyButton()

btnMyButton.Show()

As you type the code in the Code window, the Complete Word box will appear displaying the properties and methods of the Button control.

Summary

We have seen that the Window Forms framework offers many controls that you can use. These controls have properties, methods, and events to help you accomplish your goals. As we have discussed, many properties of controls can be changed at design-time and at runtime. We have seen many examples of just how to change those properties at runtime.

Sometimes you need a reusable object for a certain functionality that is not built into the Windows Forms framework. For these, applications components are just the ticket. Not only do components provide a great way to reuse code, but they also allow you to get the exact functionality you need.

Controls are components with user interface capabilities. You can create properties for controls  the same way you saw properties for components created in this chapter. More often than not, you do not need a whole new control, but simply a change to one of the many powerful controls built into the Windows Forms framework. You have seen how to make such a change and get a control to do exactly what you want.

Solutions Fast Track

Built-in Controls

·     The Windows Forms framework offers many controls that you can use to build applications.

·     The built-in controls have many properties, methods, and events in common.

·     You can change many of the properties of built-in controls both at design-time and runtime.

Creating Custom Windows Components

·     At times, you need a custom component to provide exactly the functionality you need.

·     Components provide reusable code in the form of objects.

·     Creating a custom component is a delicate multistep process.

Creating Custom Windows Controls

·     Sometimes the built-in controls do not provide the functionality you need.

·     A control is a component with user interface capabilities.

·     Often, you can extend an existing control instead of creating a new one.

Frequently Asked Questions

Q: Does Visual Basic .NET support component and control creation?

A: Yes, Visual Basic .NET allows you to create your own components and controls. Components can be used to provide reusable code in the form of objects.

Q: Can I choose more than one control to collect a piece of information from the user?

A: Yes, many controls allow you to collect input from the user. However, some controls are better than others for collecting and validating specific types of information, like dates and times.

Q: Can the properties of controls be changed at runtime?

A: Many properties of controls can be changed at runtime. However, other properties are read-only at runtime.

Q: How do I programmatically add items to a combo box?

A: You can programmatically add items to a combo box and other controls by using the Add  method of the Items collection.

 

Q: Should I create my own controls?

A: You only need to create your own controls when the built-in controls do not provide the functionality you need, or if they cannot be extended to provide that functionality.

<< Go back to Page 1
  Contact Us |  | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy