Home

Introduction to Application Design

 

Message Boxes

 

Introduction

A message box is a special dialog box used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything in the dialog box. To support message boxes, the Visual Basic language provides a function named MsgBox. To support message boxes, the .NET Framework provides a class named.

To display a simple message box, you can use the MsgBox() function with the following formula:

MsgBox(Message)

Inside the parentheses, pass a string. Here is an example:

 
Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Welcome to Microsoft Visual Basic")
End Sub
Message Box

If the message is made of different sections, you can concatenate them using the & operator. You can also first declare a String variable, initialize it, and pass it to the function.

To create a message box using the .NET Framework, you can call the Show() method of the MessageBox class using the following formula:

MsgBox(Message)

As done for the MsgBox() function, pass a string to the method. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Welcome to Microsoft Visual Basic")
End Sub

In our lessons, we will mostly use the MsgBox() function, not because it is better than the MessageBox class. It is simply a preference; but it is also because these lessons are for Microsoft Visual Basic, so we give preference to its own (rich) library.

The Return Value of a Message Box

Besides displaying a message, a message box can be used to let the user make a decision by clicking a button and, depending on the button the user would have clicked, the message box would return a value. To be able to return a value, the MsgBox() function is declared as follows:

Public Shared Function MsgBox ( _
	Prompt As Object, _
	<OptionalAttribute> Optional Buttons As MsgBoxStyle = MsgBoxStyle.OkOnly, _
	<OptionalAttribute> Optional Title As Object = Nothing _
) As MsgBoxResult

The value returned by a message box corresponds to a button the user would have clicked (on the message box). The return value of the MsgBox() function is based on the MsgBoxResult enumeration. The buttons and the returned values are as follows:

If the User Clicks Button Caption Integral Value
OK OK 1
Cancel Cancel 2
Abort Abort 3
Retry Retry 4
Ignore Ignore 5
Yes Yes 6
No No 7

The Buttons of a Message Box

If you create a simple message box by providing only the message, it would appear with only one button labeled OK. If you want the user to be able to make a decision and communicate it to you, provide a second argument. The second argument must be based on the MsgBoxStyle enumeration. When it comes to buttons, some members of this enumeration are:

To Display MsgBoxStyle Integral Value
OK OKOnly 0
OK Cancel OKCancel 1
Abort Retry Ignore AbortRetryIgnore 2
Yes No Cancel YesNoCancel 3
Yes No YesNo 4
Retry Cancel RetryCancel 5

To use any of these combinations of buttons, call the MessageBoxStyle enumeration and access the desired combination. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Now we will move to the next step", MsgBoxStyle.OkCancel)
End Sub

This would produce:

Message Box With Buttons

 

The Caption of a Message Box

If you create a simple message box by providing only the message, the dialog box would appear with the name of the project in the title. To allow you to specify a caption of your choice, provide a second string as the third argument to the MsgBox() function. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Now we will move to the next step", _
                     MsgBoxStyle.OkCancel, "Lessons Objectives")
End Sub

This would produce:

Message Box

The Icon of a Message Box

To enhance the appearance of a message box, you can display an icon on it. To support icons, the MsgBoxStyle enumeration provides the following additional members:

To Display MsgBoxStyle Integral Value
Critical Critical 16 
Question Question 32
Exclamation Exclamation 48
Information Information 64

To apply one of these buttons, combine its style with that of the button, using the OR operator. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Are you ready to provide your credit card information?", _
               MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
               "Customer Order Processing")
End Sub

This would produce:

Message Box With an Icon

The Default Button of a Message Box

When a message box is configured to display more than one button, the operating system is set to decide which button is the default. The default button has a thick border that sets it apart from the other button(s). If the user presses Enter, the message box would behave as if the user had clicked the default button. If the message box has more than one button, you can decide what button would be the default. To support the default button, the MsgBoxStyle enumeration provides the following additional options:

MsgBoxStyle Integral Value If the message box contains more than one button, the default button would be
DefaultButton1 0 the first
DefaultButton2 256 the second
DefaultButton3 512 the third

Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        MsgBox("Are you ready to provide your credit card information?", _
               MsgBoxStyle.YesNoCancel Or _
               MsgBoxStyle.Question Or _
               MsgBoxStyle.DefaultButton2, _
               "Customer Order Processing")
End Sub

Message Box With an Icon

The Input Box

 

Introduction

An input box is a specially designed dialog box that allows the programmer to request a value from the user and use that value as necessary. An input box displays a title, a message to indicate the requested value, a text box for the user, and two buttons: OK and Cancel. Here is an example:

Input Box

When an input box displays, it presents a request to the user who can then provide a value. After using the input box, the user can change his or her mind and press Esc or click Cancel. If the user provided a value and want to acknowledge it, he or she can click OK or press Enter. This would transfer the contents of the text box to the application that displayed the input box.

Creating an Input Box

 

To support input boxes, the Visual Basic library provides a function named InputBox. Its syntax is:

Public Function InputBox( _
      ByVal Prompt As String, _
      Optional ByVal Title As String = "", _
      Optional ByVal DefaultResponse As String = "", _
      Optional ByVal Xpos As Integer = -1, _
      Optional ByVal YPos As Integer = -1 _
) As String

The only required argument of this function is the message that prompts the user. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        InputBox("Enter Student's Date of Birth")
End Sub

This would produce

Input Box   

When calling the InputBox() function, if you pass only the first argument, the input box would display the name of the application in the title bar. If you want, you can specify your own caption through the Title argument. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        InputBox("Enter Student's Date of Birth", _
                       "Red Oak High School - Student Registration")
End Sub

This would produce

Input Box   

When reading the message on the Input box, the user is asked to enter a piece of information. The type of information the user is supposed to provide depends on you, the programmer. Therefore, there are two important things you should always do. First you should let the user know the type of information requested. Is it a number (what type of number)? Is it a string (such as the name of a country or a customer's name)? Is it the location of a file (such as C:\Program Files\Homework)? Are you expecting a Yes/No True/False type of answer (if so how should the user provide it)? Is it a date (if it is a date, what format is the user supposed to enter)? These questions indicate that you should state a clear request to the user.

To assist the user with the type of value you are expecting, you can give an example or a type. To support this, the InputBox() function is equipped with the third argument as a string. When passing it, you can provide a sample value that the user would follow. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        InputBox("Enter Student's Date of Birth", _
                 "Red Oak High School - Student Registration", _
                 "MM/DD/YYYY")
End Sub

This would produce:

Input Box

The last two arguments, XPos and YPos, allow you to specify the default position of the input box when it comes up the first time.

After typing a value, the user would click one of the buttons: OK or Cancel. If the user clicks OK, you can retrieve the value the user would have typed. It is also your responsibility to find out whether the user typed a valid value or not. Because the InputBox() function returns a string, it has no mechanism of validating the user's entry. Therefore, if necessary, you must convert the return value of the input box when the user clicks OK. Here is an example:

Private Sub btnMessage_Click(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnMessage.Click
        Dim strDOB As String

        strDOB = InputBox("Enter Student's Date of Birth", _
                 "Red Oak High School - Student Registration", _
                 "MM/DD/YYYY")

        If IsDate(strDOB) Then
            MsgBox("The student was born on " & CDate(strDOB).ToString("D"), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Red Oak High School - Student Registration")
        Else
            MsgBox("You provided an invalid value", _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Red Oak High School - Student Registration")
        End If
End Sub

Dynamic Control Creation

 

Introduction

The objects used in a Windows application are defined in various assemblies. To add one of these controls to your application, you must first know the name of its class. With this information, you can declare a variable of its class. For example, a command button is an object of type Button that is based on the Button class. The Button class is defined in the System.Windows.Forms namespace of the System.Windows.Forms.dll assembly. Based on this, to create a button, you can create a variable of type Button. Here is an example:

Imports System
Imports System.Windows.Forms

Module Exercise

    Public Class Exercise
        Inherits Form

        Private btnSubmit As Button

        Public Sub New()

        End Sub

        Public Shared Function Main() As Integer

            Application.Run(New Exercise())
            Return 0

        End Function
    End Class
End Module

After declaring the variable, you can use the New operator to allocate memory for it:

Public Sub New()
            btnSubmit = New Button()

End Sub

This is also referred to as dynamically creating a control. After declaring the variable and allocating memory for it, the control is available but does not have a host, which makes it invisible. A control must be positioned on a container, like a form. The Form class itself contains a member variable named Controls. This member holds a list of the objects that are placed on the form. To specify that a control you have instantiated must be positioned on a form, the Controls member has a method named Add. Therefore, to make an object part of the form, pass its variable to the Add() method. Here is an example:

Imports System
Imports System.Windows.Forms

Module Exercise

    Public Class Exercise
        Inherits Form

        Private btnSubmit As Button

        Public Sub New()
            btnSubmit = New Button()
            Controls.Add(btnSubmit)
        End Sub

        Public Shared Function Main() As Integer

            Application.Run(New Exercise())
            Return 0

        End Function
    End Class
End Module

This makes it possible for  the control to appear on the form when the form displays to the user:

The two techniques of visual addition of objects and dynamic creation are the most used to add Windows controls to an application. The Windows controls are also called components.

Initializing the Components

Because there can be many controls used in a program, instead of using the constructor to initialize them, the Visual Studio standards recommend that you create a sub procedure called InitializeComponent to initialize the various objects used in your application. Then simply call that method from the constructor of your form. This would be done as follows:

Imports System
Imports System.Windows.Forms

Module Exercise

    Public Class Exercise
        Inherits Form

        Private btnSubmit As Button

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()

            btnSubmit = New Button()
            Controls.Add(btnSubmit)

        End Sub

        Public Shared Function Main() As Integer

            Application.Run(New Exercise())
            Return 0

        End Function
    End Class
End Module

Notice that the control is created in the InitializeComponent() method.

Using a Partial Class

Starting in Microsoft Visual Basic 2005, and probably getting close to C++, you can use two files to create and use a form. Each file would hold a partial definition of the class. As done in a header file of a C++ application, the first file in VBasic would hold the variable  or control declarations. While in C++ a header file holds the same name (but different extensions) as its corresponding source file, because VBasic does not have the concepts of header and source file, each file must have a different name. In Microsoft Visual Basic, the name of the first file of a form starts with the name of the form, followed by a period, followed by Designer, followed by a period, and followed by the vb extension.

Components Tracking on an Application

As you add and remove components on an application, you need a way to count them to keep track of what components, and how many of them, your application is using. To assist you with this, the .NET Framework provides a class named Container. This class is defined in the ComponentModel namespace that is itself part of the System namespace. To use a variable of this class in your application, declare a variable of type Container. Because no other part of the application is interested in this variable, you should declare it private. This can be done as follows:

Imports System
Imports System.Windows.Forms

Module Exercise

    Public Class Exercise
        Partial Public Class Exercise
            Inherits Form

            Private btnSubmit As Button

            Dim components As System.ComponentModel.Container

            Public Sub New()
                InitializeComponent()
            End Sub

            Public Sub InitializeComponent()
                btnSubmit = New Button()
                
                Controls.Add(btnSubmit)
            End Sub


        End Class

        Public Shared Function Main() As Integer

            Application.Run(New Exercise())
            Return 0

        End Function

    End Class
End Module

After this declaration, the compiler can keep track of the components that are part of the form.

Control Derivation

If you are using a .NET Framework control, you must know the name of the class on which the control is based (and each control is based on a particular class). If you have examined the types of classes available but none implements the behavior you need, you can first locate one that is close to the behavior you are looking for, then use it as a base to derive a new class.

To derive a class from an existing control, you can use your knowledge of inheritance. Here is an example:

Public Class Numeric
        Inherits System.Windows.Forms.TextBox

End Class

If you want to perform some early initialization to customize your new control, you can declare a constructor. Here is an example:

Public Class Numeric
        Inherits System.Windows.Forms.TextBox

        Public Sub New()

        End Sub
End Class

Besides the constructor, in your class, you can add the fields and methods as you see fit. You can also use it to globally set a value for a variable of the parent class. Once the control is ready, you can dynamically use it like any other control. Here is an example:

Imports System
Imports System.Windows.Forms

Module Exercise

    Public Class Numeric
        Inherits System.Windows.Forms.TextBox

        Public Sub New()

        End Sub
    End Class

    Public Class Exercise
        Partial Public Class Exercise
            Inherits Form

            Private btnSubmit As Numeric

            Dim components As System.ComponentModel.Container

            Public Sub New()
                InitializeComponent()
            End Sub

            Public Sub InitializeComponent()
                btnSubmit = New Numeric()
                
                Controls.Add(btnSubmit)
            End Sub


        End Class

        Public Shared Function Main() As Integer

            Application.Run(New Exercise())
            Return 0

        End Function

    End Class
End Module

This produce:

The Properties Window

 

Introduction

A property is a piece of information that characterizes or describes a control. It could be related to its location or size. It could be its color, its identification, or any visual aspect that gives it meaning. The properties of an object can be changed either at design time or at run time. You can also manipulate these characteristics both at design and at run times. This means that you can set some properties at design time and some others at run time.

To manipulate the properties of a control at design time, first select it on the form. While a control is selected, use the Properties window to manipulate the properties of the control at design time. To access the Properties window if it is not visible:

  • On the main menu, you can click View -> Properties Window
  • On the form, you can right-click anything (either the form itself or any control positioned on it) and click Properties
  • The shortcut to display the Properties window is F4

Description

The Properties window uses the behaviors we reviewed in Lesson 1 about auto-hiding, docking, floating or tabbing the tools that accompany Microsoft Visual Studio 2005. This means that you can position it on one side of the screen or to have it float on the screen as you wish.

The Properties window is divided in 5 sections:

The Properties window starts on top with a title bar, which displays the string Properties. If the window is docked somewhere, it displays the Window Position Window Position, the Auto-Hide Auto-Hide, and the Close Close buttons on its right side. If the window is floating, it would display only the Close button.

Under the title bar, the Properties window displays a combo box. The content of the combo box is the name of the form plus the names of the controls currently on the form. Besides the technique we reviewed earlier to select a control, you can click the arrow of the combo box and select a control from the list:

Under the combo box, the Properties displays a toolbar with 4 buttons.

Under the toolbar, the Properties window displays the list of properties of the selected control(s). On the right side, the list is equipped with a vertical scroll bar. The items in the Properties window display in a list set when installing Microsoft Visual Studio. In the beginning, you may be regularly lost when looking for a particular property because the list is not arranged in a strict order of rules. You can rearrange the list. For example, you can cause the items to display in alphabetic order. To do this, on the toolbar of the Properties window, click the Alphabetic button . To restore the list, you can click the categorized button Categorized.

Two lists share the main area of the Properties window. When the list of properties is displaying, the Properties button is clicked Properties. The second is the list of events. Therefore, to show the events, you can click the Events button . If the events section is displaying, to show the list of properties, you can click the Properties button Properties.

Under the list of properties, there is a long bar that displays some messages. The area is actually a help section that displays a short description of the property that is selected in the main area of the Properties window.

Accessing the Properties of One or More Controls

Based on a previous description,

  • If the Properties window is already displaying, to access the properties of the form or of a control, simply click it
  • If the Properties window is not displaying, to access the characteristics of an object, right-click either the form or a control on the form and click Properties
  • If the Properties window is not available, to access the characteristics, click either the form or a control on the form and, on the main menu, click View -> Properties

When a control is selected, the Properties window displays only its characteristics:

You can also change some characteristics of various controls at the same time. To do this, first select the controls on the form and access the Properties window:

When various controls have been selected:

  • The Properties window displays only the characteristics that are common to the selected controls
  • The combo box on top of the Properties window is empty
  • Some fields of the Properties appear empty because the various controls that are selected have different values for those properties

Practical LearningPractical Learning: Introducing the Properties Window

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the Templates list, click Windows Application
  3. Set the Name to Exercise4 and click OK

Properties Categories

 

Introduction

Each field in the Properties window has two sections: the property’s name and the property's value:
 


The name of a property is represented on the left column. This is the official name of the property. The names of properties are in one word. You can use this same name to access the property in code.

The box on the right side of each property name represents the value of the property that you can set for an object. There are various kinds of fields you will use to set the properties. To know what particular kind a field is, you can click its name. To set or change a property, you use the box on the right side of the property’s name: the property's value, also referred to as the field's value.

Practical LearningPractical Learning: Displaying the Properties Window

  • To display the Properties windows, on the main menu, click View -> Properties Window

Empty Fields

Property Empty  

By default, these fields have nothing in their value section. Most of these properties are dependent on other settings of your program. For example, you can set a menu property for a form only after you have created a menu.

To set the property on such a field, you can type in it or select from a list. 

 

Practical LearningPractical Learning: Checking Empty Fields

  • Click the body of the form.
    In the Properties windows, notice that the AccessibleName and the Tag fields are empty

Text Fields

There are fields that expect you to type a value. Most of these fields have a default value. Here is an example:

Property Text

To change the value of the property, click the name of the property, type the desired value, and press Enter.

While some properties, such as the Text, would allow anything, some other fields expect a specific type of text, such as a numeric value.

Practical LearningPractical Learning: Checking Text Fields

  1. In the Properties windows, click Text and notice that it contains a string in bold characters
  2. Click (Name) and notice that it contains some bold characters

Numeric Fields

Some fields expect a numeric value. In this case, you can click the name of the field and type the desired value. Here is an example:

Numeric Property

. If you type an invalid value, you would receive a message box notifying you of the error:

Error

When this happens, click OK and type a valid value. If the value is supposed to be an integer, make sure you don't type it as a decimal number.

Practical LearningPractical Learning: Checking Numeric Fields

  1. In the Common Controls section of the Toolbox, click NumericUpDown and click the form
  2. While the control is still selected on the form, in the Properties windows, click Value and notice that it contains a number string in bold characters
  3. Click the DecimalPlaces, the Increment, the Maximum, and the Minimum fields to see that they contain numeric values:
     

Date-Based Fields

Some fields expect you to enter a date. You must type a valid date recognized by the operating system and the Regional and Language Settings in Control Panel. If you enter an invalid date, you would receive an error.

Practical LearningPractical Learning: Checking Date and Time Fields

  1. In the Common Controls section of the Toolbox, click DateTimePicker and click the form
  2. While the control is still selected on the form, in the Properties windows, click Value and notice that it contains a date and time value
  3. Click the MinDate and the MaxDate fields to see their values:
     

Expandable Fields

 
Expandable Property Some fields have a + button. This indicates that the property has a set of sub-properties that actually belong to the same property and are defined together. To expand such a field, click its + button and a – button will appear:
Properties

To collapse the field, click the – button.

Some of the properties are numeric based, such as the Location or the Size. With such a property, you can click its name and type two numeric values separated by a comma. Some other properties are created from an enumeration or a class. If you expand such a field, it would display various options. Here is an example from the Font property:

With such a property, you should select from a list.

Practical LearningPractical Learning: Checking Expandable Fields

  1. Click an empty area of the form to select the form
  2. In the Properties window, click the + button of the Font field to expand it and notice that it display some previously hidden items

Boolean Fields

 
Some fields can have only a True or False value. To change their setting, you can either select from the combo box or double-click the property to toggle to the other value.
 

Practical LearningPractical Learning: Checking Boolean Fields

  1. In the Properties window click Enabled and notice that it displays True
  2. Under Font, click Bold and notice that it displays False 

Action Fields

Some fields would require a value or item that needs to be set through an intermediary action. Such fields display an ellipsis button Ellipsis . When you click the button, a dialog box would come up and you can set the value for the field.
Property Action
 

Practical LearningPractical Learning: Checking Action Fields

  1. In the Common Controls section of the Toolbox, click PictureBox and click the form
  2. While the control is still selected on the form, in the Properties windows, click Image and notice that the field displays an ellipsis button Ellipsis Button
  3. Click the ellipsis button and notice that a dialog box comes up
  4. Click Cancel

List-Based Fields

To change the value of some of the fields, you would use their combo box to display the available values. After clicking the arrow, a list would display:

Property Selection

There are various types of list-based fields. Some of them display just two items. To change their value, you can just double-click the field. Some other fields have more than two values in the field. To change them, you can click their arrow and select from the list. You can also double-click a few times until the desired value is selected.

Practical LearningPractical Learning: Checking List-based Fields

  1. Click an empty area of the form to select the form
  2. In the Properties window, click FormBorderStyle and notice that it displays an arrow button of a combo box
  3. Press Alt and the down arrow key to display the list
  4. Press Esc

Area-Selection Fields

Some properties provide a window from where you can select the desired option. The field primarily displays the arrow of a combo box. To use the field, you click the arrow of the combo box and the window appears. Here are examples:

Alignment Back Color

After expanding the window, you can select the desired option. We will eventually review them.

Practical LearningPractical Learning: Checking Area-Selection Fields

  1. On the form, click one of the controls
  2. In the Properties window, click Dock and click the arrow of its combo box
  3. Notice the window that comes up and press Esc
 
 

Previous Copyright © 2008-2009, yevol.com Next