Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать
The database file for this appendix is located on the companion Web site for this book. Copy the Mailman.mdb file from the site onto your system. This is done to save you time in creating a database.
You will also have to create a system DSN entry in your computer's ODBC management center. To do this, select Start Settings Control Panel and double-click ODBC Data Sources to open the ODBC definition window. Make an entry in the System DSN tab by clicking the Add PushButton and fill in the appropriate values. For the application that is being designed, the name was given as mailman, and the database was named the same.

The next thing that you need to do is to create another form that allows the user of your application to navigate through your database tables, adding, editing, or deleting the records as they see fit.

Creating data-aware forms

Creating data-aware forms involves two stages. First, you need to make VB.NET aware that a data source is available to it. Second, you need to build the form with the Data Form Wizard. Thankfully, both of these stages are combined through the use of the Data Form Wizard.

Note

Note

Specifying the database and tables

To establish the database connection and designate the tables to be used, complete the following steps:

1. On the Solution Explorer pane, right -click the application name and select the add windows form menu item that appears in the pop-up menu after you click the first-level add option. As before (refer to Figure A-6), you will select the add new windows form option. However, this time, in the subsequent window, you will select the Data Form Wizard option rather than the default of Windows form.

2.Name the new form frmAddress for the purposes of this exercise, and then click the Open button. This will start the wizard process.

3.After clicking the Next button on the first informational screen, you will

be presented with a window similar to that shown in Figure A-9, which asks you to either create a new dataset or use an existing one. Because a dataset doesn't already exist in this project, you are going to create a new dataset called mailman.

Figure A-9: Second step of the Data Form Wizard

4. After you type the "mailman" dataset name, click the Next button to continue through the Data Form Wizard.

5. Next you are asked for a connection to use. If a connection to this database already exists, use it; however, if one does not exists, then click the New Connection button and select the correct driver (which is "Microsoft Jet 4.0 OLE DB Provider" for MS-Access tables) on the Provider tab.

6. After selecting the appropriate provider you will need to click on the Next pushbutton to move the wizard to the connection tab. Here you should click on the Browse PushButton (signified by the ellipses ... ) and locate the mailman.mdb file that you should have moved onto your own system.

7. The completed Connection tab should look similar to that shown in Figure A-10. If you are not sure whether you have set up the ODBC settings properly, or the other options that had to be set to use the Mailman.mdb database and file, be sure to test the connection by clicking the Test Connection button at the bottom of this Connection tab.

Figure A-10: Completed connection portion of Data Form Wizard

8. After obtaining a successful connection to the database, the wizard process will ask what parts of the database structures you will be accessing: tables, views, or stored procedures. For the purposes of this application, simply select the table called addresses under the tables list and click the button between the two panes that moves the selection from the left pane to the right pane. Click the Next button to move to the next stage of the Data Form Wizard.

Now that you have connected to the database and told the wizard what table(s) you want to use from that database, the next step is to tell the wizard what fields you want to use on the form that will eventually be built.

Specifying the form fields

To establish the fields to be used on the forms you are building, complete the following steps:

1. After clicking Next in the Data Form Wizard at the end of the previous section, you would have been presented with a window asking you what data columns you want to display on the subsequent form.

Figure A-11 shows the column selection page of the wizard with a few of the columns selected. Select the columns that you want and click the Next button.

Figure A-11: The field selection page of the Data Form Wizard

2. Click on the Next button to be taken to the Display Style page of this wizard. Here you can select how the form will automatically present the information to you when the application is running. The options are self-explanatory, so simply select the options you want. To see how it has been done in this example, review the options selected in Figure A-12. The options chosen here are to show one data record at a time and to have the offered controls included on the created form.

Figure A-12: Data display page of the Data Form Wizard

3. Because this is the last option in the wizard, click the Finish button to complete the process.

The new form will be created and added to your solution. Feel free to rename the text labels that are created for you to something more descriptive, and to lay out the other controls to suit your own design. As you will be able to see, the controls are arranged

alphabetically rather than how they are defined in the database table, so you probably will always need to rearrange the forms that are generated by the Data Form Wizard. Also, if earlier in the process you commented out the menu code that references this form, be sure to return to that code and reactivate it. Then, build your solution and run it to see what it looks like. The running application should look similar to that shown in Figure A-13.

Figure A-13: Running application with the Address form open and operational

Data Types and Variables

Some fundamental logical features make up a programming language. The way data is handled and processed within the memory of the computer is accomplished through entities known as variables. Variables are defined in a way that describes the data that is contained within them, both in name and in content. For example, if you are trying to decide whether something is on or off or true or false, then you use the Boolean variable data type to house the information and may call it lCompleted. If you were trying to store somebody's address, you typically store that in a String data type variable.

Because many of these variables take up memory space, you should follow some simple guidelines for resource conservation. Although it seems like a trivial matter to be concerned with 2 bytes of space instead of 8 bytes of space on 128MB of RAM, it would not take too long to use up a fair portion of your computer's resources. The best rule to follow here is not to be too casual in your variable definitions. Don't use a Long data type when a Single data type will do the job. But also try to keep in mind what the upper limits of the variable is expected to reach, and make allowances for it. Don't sell yourself short either, because you can bet that you will be revisiting code in about a year when your computer application fails because some variables are running out of resource space. Table A-3 is the complete list of variable data types; however, this discussion focuses only on the more commonly used data types. Check the VB.NET product manual or online help for details on the other available data types if you think you may need to use them.

 

Table A-3: Visual Basic data types

 

 

 

 

 

 

 

 

 

 

 

Data Type

 

Memory

 

Value Range

 

 

Name

 

Storage

 

 

 

 

 

 

Requireme

 

 

 

 

 

 

nts

 

 

 

 

 

 

 

 

 

 

 

Boolean

 

1 byte

 

True or False

 

 

 

 

 

 

 

 

 

Byte

 

1 byte

 

0 to 255 (unsigned)

 

 

 

 

 

 

 

 

 

Table A-3: Visual Basic data types

 

 

 

 

 

 

 

 

 

 

 

Data Type

 

Memory

 

Value Range

 

 

Name

 

Storage

 

 

 

 

 

 

Requireme

 

 

 

 

 

 

nts

 

 

 

 

 

 

 

 

 

 

 

Char

 

2 bytes

 

0 to 65,535 (unsigned)

 

 

 

 

 

 

 

 

 

Date

 

8 bytes

 

January 1, 1 AD to December 31,

 

 

 

 

 

 

9999

 

 

 

 

 

 

 

 

Decimal

 

12 bytes

 

+/

 

 

 

 

 

 

79,228,162,514,264,337,593,543,950,

 

 

 

 

 

 

335 with no decimal point; +/-

 

 

 

 

 

 

7.9228162514264337593543950335

 

 

 

 

 

 

with 28 places to the right of the

 

 

 

 

 

 

decimal; smallest non-zero number is

 

 

 

 

 

 

+/-

 

 

 

 

 

 

0.0000000000000000000000000001

 

 

 

 

 

 

 

 

 

Double

 

8 bytes

 

-1.79769313486231E308 to -

 

 

(double-

 

 

 

4.94065645841247E-324 for negative

 

 

values;preci

 

 

 

4.94065645841247E-324 to

 

 

sion floating-

 

 

 

1.79769313486232E308 for positive

 

 

point)

 

 

 

values

 

 

 

 

 

 

 

 

 

Integer

 

4 bytes

 

-2,147,483,648 to 2,147,483,647

 

 

 

 

 

 

 

 

 

Long (long

 

8 bytes

 

-9,223,372,036,854,775,808 to

 

 

integer)

 

 

 

9,223,372,036,854,775,807

 

 

 

 

 

 

 

 

 

Object

 

4 bytes

 

Any type can be stored in a variable of

 

 

 

 

 

 

type Object

 

 

 

 

 

 

 

 

 

Short

 

2 bytes

 

-32,768 to 32,767

 

 

 

 

 

 

 

 

 

Single

 

4 bytes

 

-3.402823E38 to -1.401298E -45 for

 

 

(single-

 

 

 

negative values; 1.401298E-45 to

 

 

precision

 

 

 

3.402823E38 for positive values

 

 

floating-

 

 

 

 

 

 

point)

 

 

 

 

 

 

 

 

 

 

 

 

 

String

 

10 bytes +

 

0 to approximately 2 billion Unicode

 

 

(variable-

 

(2 * string

 

characters

 

 

length)

 

length)

 

 

 

 

 

 

 

 

 

 

 

User-

 

Sum of the

 

Each member of the structure has a

 

 

Defined

 

sizes of its

 

range determined by its data type and

 

 

Type

 

members

 

independent of the ranges of the other

 

 

(structure)

 

 

 

members

 

 

 

 

 

 

 

 

Boolean

Boolean is typically used for continuation testing or simple On/Off, True/False conditions. You can use a Boolean variable to continue a programming loop until a certain condition becomes true. The following code is an example of this:

Dim lFinished as Boolean

lFinished = FALSE

While lFinished = FALSE

'Code...

'Code...

If X = Y then

lFinished = TRUE

End if

Wend

The preceding program will run in a continuous loop until either lFinished becomes something other than False or your computer hangs because of the loss of resources.

String

The String data type is as simple as it sounds. It is used to store strings of text (alphabetic, numeric, and special characters) in memory until it is accessed. For example, when e-mail address information is saved to a database, it is usually processed through a String data type variable. Strings can be names, addresses, phone numbers, Web addresses, and the like. The following code is an example:

Dim strFirstName as String

strFirstName = "Peter"

Date

Date, too, is straightforward. This data type is used to store date information that is to be processed by a program. For example, the date that an entry is made to a database is quite often used for audit-trail purposes, and this information would be processed with a Date data type. The system time is also stored as part of this data type and can be drawn out separately if desired through the use of built-in functions. The following code is an example:

Dim dRightNow as Date

dRightNow = Today()

Integer

Integer is the data type for whole numbers. Numbers are used in programming for such things as counting iterations in a For Next loop, storing phone numbers, and counting the number of employees you have. The Integer data type is ideal for these situations. It should not be used, however, for financial or detailed math processes in which remainders or decimals are to be used. The following code is an example of the Integer data type in use:

Dim iCounting as Integer

iCounting = 1

Single

The Single data type is typically used for financial calculations or any other math functions that require the use of a decimal. Other decimal-handling data types exist, but this one seems to be the most predominantly used. The following code is an example of the Single data type in use:

Dim sMyCash as Single

sMyCash = 1000.02

Note As you may notice in some of the code written so far is following a naming convention known as modified Hungarian. It was named after the programmer who devised it, he worked for Microsoft his nationality happen to be Hungarian. In this naming convention variables are named with a prefix denoting their data type and with capital letters for the major name sections. For example, a variable named strFirstName is obviously a string variable (with the str

prefix), and it holds a string that happens to be a first name value. The initial caps on the major named portions are used for readability. When scanning through code one can visually see much better how a variable is named and how it is defined. Perform a Web search for this topic to gather more information on naming conventions for variables, and check out http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnw98bk/html/variablenameshungariannotation.asp.

Understanding DIM statements

As in the previous sections, there is a certain way to actually define a variable in memory space. By using the DIM command followed with a variable name and its designated data type, you can reserve memory space for a variable. Following is the complete syntax of the DIM command. For now, however, the previous examples are sufficient for getting started using this command.

DIM [WithEvents] varname[([subscripts])] [As [New] type] [= initexpr]

Although this syntax looks complex, you really need to concern yourself only with the DIM keyword itself, a variable name, and the data type that you want the variable to be. Optionally, you can set the variables initial value at the same time as you define it. Consider the following DIM statement:

Dim sMySalary as Single = 100000.02

The variable is called sMySalary and it is being defined as a Single data type. The initial value of $100,000.02 is being assigned to it. You can also define multiple variables with the same DIM command. The following statement defines three variables within the same statement, all with different data type assignments:

Dim iCounter as Integer, strFirstName as String, dRightNow as Date

Variable scope

The life expectancy of a variable is another matter to be considered when one is to be defined. Does a variable exist through the life of the running program, within a certain module of the application, or only within a certain subroutine of a particular form?

Designating the answer to this is called defining the scope of a variable.

Visual Basic .NET enables you to define variables on at least three different levels. Variables defined at the application level exist in memory for the life of the application (while it is running). Programmers have to be conservative here (as well with the use of memory and system resources), because if they define a number of variables to be globally accessible and yet do not use them efficiently, then they are wasting system resources in the holding of variables and memory space when only being used under certain conditions.

Defining a phone number variable as globally accessible, for example, would be a great waste of system resources, whereas defining it at the module level would make sense. If you define a variable at the module level (in the open script of a form, for example), then that variable is accessible to any subprocedures within that form. And finally, if a variable is defined within a subprocedure or function (the code behind a push button, for example), then that variable only exists and is only accessible to that subprocedure that called it into existence.

Some ways around this limitation exist, by passing and returning variables to a routine. These variable scopes, as discussed, are sometimes called global, private, and local, respectively. It is a common programming "best practice" to define variables with as limited a scope as possible.

Operators

Two major categories are involved in the decision processes of computer languages, and VB.NET is no exception. The first category is that of operators and the second one is know as logical flow (discussed in the next section).

Operators are well known in the world of math. Table A-4 shows each operator's symbol with a brief description of its function. This table goes from the simplest operator to the more complex, and typically more powerful, operators. So, after you have mastered the more general operators, you should be able to employ the more complex ones relatively easily. Following the table are some specific examples of operators and how they are used in programming code.

Table A-4: VB.NET operators

Symbol

Name of

 

Description

Operator

 

 

+

 

Plus

 

Used in

 

 

(addition)

 

adding two

 

 

 

 

or more

 

 

 

 

values

 

 

 

 

together

 

 

 

 

 

-

 

Minus

 

Used in

 

 

(subtraction)

 

subtracting

 

 

 

 

two or more

 

 

 

 

values from

 

 

 

 

each other

 

 

 

 

 

/

 

Division

 

Used in

 

 

 

 

dividing one

 

 

 

 

value into

 

 

 

 

another

 

 

 

 

 

*

 

Multiplication

 

Used in

 

 

 

 

multiplying

 

 

 

 

two or more

 

 

 

 

values

 

 

 

 

together

 

 

 

 

 

=

 

Equals

 

Used in

 

 

 

 

assigning

 

 

 

 

the results

 

 

 

 

of a

 

 

 

 

calculation

 

 

 

 

to a variable

 

 

 

 

 

>

 

Greater than

 

Used in

 

 

 

 

determining

 

 

 

 

if one

 

 

 

 

variable's

 

 

 

 

value is

 

 

 

 

larger than

 

 

 

 

another's

 

 

 

 

 

<

 

Less than

 

Used in

 

 

 

 

determining

 

 

 

 

if one

 

 

 

 

variable's

 

 

 

 

value is

 

 

 

 

smaller than

 

 

 

 

another's

 

 

 

 

 

>=

 

Greater than

 

Used in

 

 

or equal to

 

determining

 

 

 

 

if one

 

 

 

 

variable's

 

 

 

 

value is

 

 

 

 

larger than

 

Table A-4: VB.NET operators

 

 

 

 

 

 

 

 

 

 

 

 

 

Symbol

 

Name of

 

Description

 

 

 

 

Operator

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

or equal to

 

 

 

 

 

 

another's

 

 

 

 

 

 

 

 

 

<=

 

Less than or

 

Used in

 

 

 

 

equal to

 

determining

 

 

 

 

 

 

if one

 

 

 

 

 

 

variable's

 

 

 

 

 

 

value is

 

 

 

 

 

 

smaller than

 

 

 

 

 

 

or equal to

 

 

 

 

 

 

another's

 

 

 

 

 

 

 

 

 

<>

 

Not equal

 

Used in

 

 

 

 

 

 

determining

 

 

 

 

 

 

if one

 

 

 

 

 

 

variable's

 

 

 

 

 

 

value is not

 

 

 

 

 

 

equal to

 

 

 

 

 

 

another's

 

 

 

 

 

 

 

 

 

Performing math on variables

 

 

 

 

 

Here are some basic examples of math functions as they are implemented in VB.NET code:

Dim iSubTotal as Integer, iTax as Single, iTotal as Single

iTax = iSubTotal * 1.10

iTotal = iSubTotal + iTax

The first line of code simply defines the variables to be used. The second line uses the multiplication operator and the equals operator, multiplying the integer value in iSubTotal by 1.10 (10 percent), and then assigns the result to the iTax variable. The next line of code uses the addition operator to simply add two variables together and assign the result to the iTotal variable.

Some math operations do not require the use of the equals operator. Consider the following code example:

Dim iCounter as integer

iCounter = 1

Do until iCounter > 50

'more code

'more code

iCounter = iCounter + 1

loop

This code is quite powerful if you need to repeat a process 50 times and no more.

Logical Flow

Our discussion now moves into the next category of how programs can flow based on simple decision processes. You thought I forgot about the other category that was mentioned in the previous section, but here it is now. There is usually a need for

programs to repeat a process for a certain length of time, or indefinitely, and VB.NET has these features built in. There are also many times when decisions must be based on the context of the code at a moment in time and that context can change depending on the application users decisions.

If Then Else Endif Decision Construct

This is a coding construct that allows the code to perform one of two or more possible steps depending on the logical evaluation of an expression. The If...Then...Else programming construct has the following syntax:

If condition [ Then ]

[ statements ]

[ ElseIf elseifcondition [ Then ]

[ elseifstatements ] ]

[ Else

[ elsestatements ] ]

End If

Simplified, the syntax looks like this:

IF lExpression [THEN]

Commands

[ELSE

Commands]

END IF

Here is a simple example of the If...Then...Else command structure in operation:

If strA = strB then

intCounter++

Else

intOtherNumber++

End If

The process here is to test the equality of strA and strB; if they are equal in value, then increase the variable called intCounter by 1. However, if strA is not equal to strB, then the Else portion of the construct is handed the controls and is processed, increasing the value of intOtherNumber by 1. So if strA has the value of "ABC", strB has the value of "ABC", intCounter has the value of 10, and intOtherNumber has the value of 15, stepping through this code once would leave intCounter holding the value of 11, and all other values would remain the same. This should give you the general idea of the use of this construct. This theme has many variations, though, so you should look into the different applications of the construct, because some of the options available could increase the efficiency of your applications.

While Loops

The While...Wend set of commands is very powerful, yet can be dangerous at the same time, because it allows for a series of other commands to run indefinitely unless an escape route is planned for it. This is also known as a programming loop, because the code loops around and around until told to stop or the computer runs out of available resources. If not controlled properly the latter can occur causing what is known as an infinite loop, which is a bad thing.

The syntax of this command allows for a few escape routes, and it is usually good to use the first one available, that being the condition that controls the start of the While loop. First, take a look at the official syntax:

While condition

Соседние файлы в папке c#