Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

INTRODUCTION TO VISUAL BASIC .NET Appendix B 861

Collections

A collection can be considered as a group of related objects. Generally, a collection is used to work with related objects. However, collections can be made to work with any data type.

Standard Collections Provided by Visual Basic .NET

Visual Basic .NET provides you with several collections that are used to organize and manipulate objects in an efficient way. Consider an example. All the controls in a form are stored in the Controls collection. Similarly, all the forms in a Visual Basic .NET project are stored in the Forms collection. An efficient way to keep track of the objects that an application needs to create and destroy during run time is provided by a collection.

Consider an example: In an application that you have created, you need to take inputs for five text boxes from the user and then validate the data entered by the user for all of them. One way in which the code can be written is to check for each of the text boxes separately. Another way, which is relatively easy, is to check using the Controls collection. Every form has a Controls collection that represents all the controls, such as command buttons, labels, text boxes, and so on that are present in the form. You can easily perform the input validation check by using the Controls collection.

NOTE

Controls is the base class for all the controls. It is included in the

System.Windows.Forms namespace and is provided by Visual Basic .NET.

You have learned about the collections in a brief overview. I will now discuss how you can create your own collections.

Creating Collections

In addition to the various standard collections that are present in Visual Basic

.NET, you can create your own collections. For collections, Visual Basic .NET

862

Part X

APPENDIXES

 

 

 

provides the Collection class. The syntax for creating a collection is discussed as follows:

Dim CollectionName As New Collection()

In the preceding syntax, the name of the collection that you want to create is specified by CollectionName. An instance of the Collection class is created, which is declared by the New keyword in the declaration statement

After the creation of the collection, you can manipulate the creation in the same way as you would manipulate the standard collections that are provided by Visual Basic .NET. However, there are some differences between the two. Consider the following example:

Dim collection1 as New Collection()

collection1 = Controls

The preceding code creates and initializes a Collection object, collection1, with the Controls collection. However, this statement displays an error message. Why is it so? The answer is that the Controls collection and the Collection class object are not interchangeable and are of different types with different usage. In addition, they do not have the same methods and also do not use the same kinds of index values.

Procedures

Consider a scenario where you need to perform a particular task repeatedly, for instance, calculating the average of marks obtained by students in a particular subject. In a situation such as this, you can group them in a procedure instead of writing the statements repeated ly. A set of statements grouped together to perform a specific task is called procedure. You can organize your applications by using procedures that allow you to chunk and group the program code logically.

After grouping the statements in a procedure, you can call the procedure from anywhere in the application. To call a procedure means to execute a statement that further instructs the compiler to execute the procedure. After executing the code in the procedure, the statement following the statement that called the procedure is executed.The statement that is called by a procedure is called a calling statement, and it includes the name of the procedure.The calling statement also includes the

INTRODUCTION TO VISUAL BASIC .NET Appendix B 863

data values that are needed by the procedure for performing the tasks that are specified. The data values are also referred to as arguments or parameters.

Consider the example of calculating average mentioned previously. In this case, you can create a procedure that accepts the maximum and minimum marks obtained by students as data values and calculate the average. To call this procedure, the statement to be called must provide the minimum and maximum marks obtained by students as parameters.

Now consider some of the advantages that are offered by procedures. The first advantage is the reusability of code. In other words, a procedure can be created and used when it is required and if any statement has to be changed, you simply need to make the changes in a single location.This is useful mainly in the case of large and complex applications.The applications that use procedures are easier to debug. Additionally, you can easily trace the errors in a procedure without debugging the entire application code.

Now consider the scope or accessibility of procedures in an application. Similar to classes and variables, procedures have a scope. A procedure is generally declared in a class or a module. Therefore, you can call a procedure from the same class or module in which it is created. The scope of the procedure depends on the access modifiers that you use while the procedures are declared. The access modifiers supported by Visual Basic .NET are listed in Table B-3.

Table B-3 Access Modifiers for Procedures

Access Modifier

Scope

Public

A procedure with a Public access modifier can be called from any class

 

or module in the application.

Private

A procedure with a Private access modifier can be called from the

 

same class or module in which it is declared.

Protected

A procedure with a Protected access modifier can be called from the

 

same class or module in which it is declared. In addition, it can be

 

called from the derived classes of the class in which it is declared.

Friend

A procedure with a Friend access modifier can be called from any class

 

or module that contains its declaration.

 

 

864

Part X

APPENDIXES

 

 

 

Based on the functionality of procedures, they can be classified as:

Sub procedures. A sub procedure is used to perform a specific task.

Function procedures. A function procedure is used to perform the specific tasks and returns a value to the calling statement.

Property procedures. A property procedure is used to assign or access a value from an object.

Event-handling procedures. An event-handling procedure is used to perform a specific task when a particular event occurs.

Arguments

As stated earlier, variables, constants, or expressions are accepted as arguments by procedures. As a result, each time a procedure that accepts arguments is called, arguments need to be passed to the procedure. Based on the data values that are passed as arguments, the result can differ for each call to a procedure. Arguments can be passed to procedures by either value or reference.

Functions

Visual Basic .NET provides various built-in functions that can be used in applications. Some of the built-in functions are MsgBox, InputBox, CStr, DateDiff, and StrComp. The Microsoft.VisualBasic namespace contains a declaration for these built-in functions. These functions can be classified based on the tasks performed by the various built-in functions. The functions can be classified as follows:

Functions to enhance your programs are performed by the Application enhancement functions. Examples of Application enhancement func-

tions are MsgBox and InputBox.

Functions to manipulate strings are performed by String functions. Examples of String functions are StrComp, Len, and Trim.

Functions to manipulate date and time values are performed by the Date function. Examples of Date functions are DateDiff, Now, and Month.

Functions to convert one data type to another are performed by the Conversion function. Examples of Conversion functions are CStr, CDate, and Val.

INTRODUCTION TO VISUAL BASIC .NET Appendix B 865

Having discussed the components of Visual Basic .NET, you can use this knowledge to create a simple application in Visual C# .NET.

Creating a Simple Visual C# .NET

Windows Application

In this section, you will create a simple Visual C# .NET Windows application. Then, I will discuss how to create the same application in Visual Basic .NET. Doing this will help you to appreciate how easy it is to convert an application created in one of the languages of the .NET Framework to another. In addition, you will be able to realize how closely the two languages of the .NET Framework, Visual Basic .NET and Visual C# .NET, are related.

Now, I will proceed with creating a simple Windows application in Visual C#

.NET. Name this application SampleWindowsApplication. This application accepts a username and password from the user. After specifying the required information, the user clicks on the Submit button. A message box showing the

text The user name and password that you have specified is accepted. is dis-

played. In addition, the Windows form consists of an Exit button that is used to exit the Windows application. To create SampleWindowsApplication, include two label controls, two text box controls, and two command controls to the Windows form. Next, change the following properties of the controls:

Form1

Name: frmAcceptUserInput

Text: Accept User Input

Label1

Name: lblUserName

Text: User Name

Label2

Name: lblPassword

Text: Password

866

Part X

APPENDIXES

 

 

 

Textbox1

Name: txtUserName

Textbox2

Name: txtPassword

PasswordChar: [*]

Button1

Name: btnSubmit

Text: submit

Button2

Name: btnExit

Text: Exit

After dragging the controls to the form, your SampleWindowsApplication looks as shown in Figure B-1.

FIGURE B-1 SampleWindowsApplication with the cont rols added

INTRODUCTION TO VISUAL BASIC .NET Appendix B 867

Now, to add the functionality to the application, you need to write code for the button controls. After adding code to the button controls, the code for the application is as shown:

using System.Drawing; using System.Collections;

using System.ComponentModel; using System.Windows.Forms; using System.Data;

namespace SampleWindowsApplication

{

public class frmAcceptUserInput : System.Windows.Forms.Form

{

private System.Windows.Forms.Label lblUserName; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.Button btnSubmit; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.TextBox txtPassword;

private System.ComponentModel.Container components = null;

public frmAcceptUserInput()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

868

Part X

 

APPENDIXES

 

 

 

 

 

 

 

 

[STAThread]

 

 

 

 

static void Main()

 

 

 

 

{

 

 

 

 

 

 

Application.Run(new frmAcceptUserInput());

 

 

}

 

 

 

 

 

private void btnSubmit_Click(object sender, System.EventArgs e)

 

 

{

 

 

Y

 

 

 

 

L

 

 

 

MessageBox.Show(“The user name and password that you have specified is

 

 

 

accepted.”);

F

 

 

 

 

 

 

 

}

 

M

 

 

}

 

 

 

 

 

 

A

 

 

 

private void btnExit_Click(object sender, System.EventArgs e)

 

 

{

E

 

Application. xit();

} } T

After creating an application in Visual C# .NET, you can create this application in Visual Basic .NET.

Creating a Simple Application

in Visual Basic .NET

The steps for creating an application in Visual Basic .NET are similar to the steps for creating an application in Visual C# .NET. Similar to Visual C# .NET, Visual Studio .NET also provides you with a template to create an application in Visual Basic .NET. To create the SampleWindowsApplication by using Visual Basic

.NET, perform the following steps:

1.On the File menu, point to the New option.

2.In the displayed list, select the Project option. The New Project dialog box is displayed.

3.In the Project Types: pane of the New Project dialog box, select the Visual Basic Projects option.

Team-Fly®

INTRODUCTION TO VISUAL BASIC .NET Appendix B 869

4.In the Templates: pane, select the Windows Application option.

5.In the Name: text box, type the name of the Windows application as

SampleWindowsApplication1.

6.Accept the default location as specified in the Location: text box. You may also choose to browse for the location where you want to save the application by clicking on the Browse button.

7.Click on the OK button to close the New Project dialog box.

Figure B-2 shows the New Project dialog box for the SampleWindowsApplication1 project in Visual Basic .NET.

FIGURE B-2 The New P roject dialog box for SampleWindowsApplication1

When you click on the OK button, Visual Studio .NET automatically creates the default files and a blank Windows form for you. Click on the Show All Files button in the Solution Explorer window to view a list of all the files created by Visual Studio .NET. Figure B-3 shows the default files and the blank form created by Visual Studio .NET.

870

Part X

APPENDIXES

 

 

 

FIGURE B-3 The default files and the blank form created by Visual Studio .NET

As you can see in Figure B-3, the blank form in Visual Basic .NET is created with an extension .vb. In addition, Visual Studio .NET creates some reference files for the SampleWindowsApplication1 project. Similar to Visual C# .NET, Visual Studio .NET creates a solution with the same name as that of the Windows application. Inside the solution, the project with the name SampleWindowsApplication1 is created.

Now, proceed with the creation of the SampleWindowsApplication1 application. To create the application, you need to add controls to the Windows form. Because Visual Basic .NET and Visual C# .NET are languages based on the .NET Framework, the IDE for the Visual Basic .NET applications is the same as that of the Visual C# .NET applications. The IDE for the Visual Basic .NET applications contains a toolbox that contains controls that you can use to create the Windows application. Figure B-4 shows the toolbox that contains standard controls for creating a Windows application in Visual Basic .NET.

INTRODUCTION TO VISUAL BASIC .NET Appendix B 871

FIGURE B-4 The toolbox for creating Windows application

From the toolbox, drag two label controls, two text box controls, and two button controls and place them on the form. Now in the Properties window of the controls, change the properties of the controls.

TIP

If the Properties window is not displayed, select the control and press the F4 key. Alternatively, you can select the Properties Window option on the View menu.

Change the following properties of the controls:

Form1

Name: Form1

Text: Accept User Input