Wal Mart Online → Best Selection
WM468X60_ko_static.gif

Last Modified:
9-15-2010

Home


Visual Basic

Introduction to VB.NET

.NET Framework

VS2008 IDE

How VB is Compiled

Start Visual Studio


Windows Form App


Save Your Work

VB OOP Programming

Visual Basic Code


Exit Code


Button Event Code

Coding Recommendations

If/Then/Else

Error List Window

Comment Syntax

Help Window

Language Essentianl

Built-In Data Types


Declare Variables

Declare Constants

Code Arithmetic Expressions

Assignment Statements

Operator Precedence

Type Casting


Math Class

String Declaration

Conversion Functions

Conversion Methods

Formatting Functions

String Formatting


Variable Scope

Enumerations

Nullable Types


Loop Constructs

For Next Loop

Do While Loop


Do Until Loop

Do...Loop-While

Do...Loop-Until


Exit Do | Exit For

Do...Loop


Nested Loops


Arrays

Array Declaration


Rnd( ) Function

Listbox Control


KeyPressEventArgs


Parallel Arrays

Key Event Args


Dynamic Arrays

Redimension Array

Set Breakpoint

Start Debugger


ReDim Preserve


MultiDimensional Arrays

DataGridView Control


Length and Sort Methods


Structures

Pad Right

Split Method

IsNumeric Function


Multiform Projects


Add Form To Project

Form Object Methods

Form Show Method

ShowDialog Method

Form Close Method

Form Accept Button

Multiform Project Example


ASP.NET Web Programming

Create Data Source


Configure Access Data Source


Add Product Class


Extract Local Database Data

Order PageLoad VB Code

Add New Web Page


Set Start Page

Display Cart Aspx Code

Display Cart Design View

Sorted List Definition

VB.NET Session State


Create CartItem Class

GetCartContents Function


Add To Cart Event Handler

Remove Cart Item Event


Clear Cart Event Handler



Invoice Total Calculate Button Event Code

Now that we have some familiarity with integrating Visual Basic code with .NET Framwork Forms, we are ready to expand the requirements of pressing the Calculate Button button. Pressing the Calculate button should give us the following procedure:

  • Value entered into Subtotal TextBox is transferred to the variable Subtotal.
    • double Subtotal=Convert.ToDouble(txtSubtotal.Text);

  • Determine DiscountPercent from the following requirements:
    • If Subtotal >= 500 then DiscountPercent = 20%.
    • If Subtotal < 500 and Subtotal >= 250 then DiscountPercent = 15%.
    • If Subtotal < 250 and Subtotal >= 100 then DiscountPercent = 10%.
    • Otherwise, DiscountPercent = 0%.

  • Multiply the Subtotal by the DiscountPercent to get a DiscountAmount.
    • DiscountAmount = Subtotal * DiscountPercent;

  • Subtract the DiscountAmount from the Subtotal to get the InvoiceAmount.
    • InvoiceAmount = Subtotal - DiscountAmount.

  • Display the DiscountPercent in the DiscountPercent TextBox.
    • txtDiscountPercent.Text = DiscountPercent.ToString("p1");

  • Display the DiscountAmount in the DiscountAmount TextBox.
    • txtDiscountAmount = DiscoutAmount.ToString("c");

  • Display the InvoiceTotal in the InvoiceTotal TextBox.
    • txtInvoiceTotal = InvoiceTotal.ToString("c");

  • Set the Focus back to the Subtotal TextBox.
    • txtSubtotal.Focus();

Visual Basic If/Then/Else Conditional Statements

By far the most common decision-making construct in programming is the if construct. The If Construct uses Boolean logic to evaluate an expression to either true or false. If the expression evaluates to true, then the block of statements after the If/Then statement is evaluated. If the statement is false, Visual Basic does not execute the statement block for the If Construct. The coding rules for Visual Basic If/Then/Else Constructs are as follows:

The syntax of the if-else statement:
	If BooleanExpression Then
		Statements
	[Else If BooleanExpression Then
		Statements]
	[Else
		Statements]
	End If
						
A Simple If/Then Statement:
	If Subtotal < 200 Then
		DiscountPercent = .15
	End If
						
An If Statement With an Else Clause:
	If Subtotal < 200 Then
		DiscountPercent = .15
	Else
		DiscountPercent = .20
	End If
						
An If Statement with ElseIf Clauses
	If Subtotal < 200 Then
		DiscountPercent = .15
	ElseIf Subtotal >= 200 And Subtotal < 300 Then
		DiscountPercent = .20
	ElseIf Subtotal >= 300 And Subtotal < 400 Then
		DiscountPercent = .25
	Else
		DiscountPercent = .30
	End If
						
Nested If Statements:
	If CustomerType = "A" Then
		If Subtotal < 200 Then
			DiscountPercent = .15
		Else
			DiscountPercent = .20
		End If
	Else
		DiscountPercent = .10
	End If
						
					
Summary
  • An If/Then statement will always contain at least one response statement.
  • An If/Then statement may have any number of ElseIf clauses
  • An If/Then statement may have 0 or 1 Else clauses
  • If you type the If keyword and the Boolean Expression, Visual Basic will automatically add the Then and End If statements.
  • If you declare a variable inside the If/Then statement - That variable only exists inside the If/Then statement.

Figure VB-31: Visual Basic If/Then/Else Statement


Visual Basic Coding Recommendations

  • Align statements with indentation and extra spaces to reflect the structure of the program.
  • Place spaces between words, operators and values to make them more readable.
  • Use blank lines before and after groups of related statements.
  • Use the line-continuation character '_' to break long lines into shorter more readable lines.

With that background it is time to develop the code for the requirements stated above. Change the code in the Calculate Button event procedure as follows:

Invoice Code 2

Figure VB-32: Visual Basic Invoice Total Calculate Button Event Handler ver 2.0


We are now going to test our code by following the steps below:

  • Press the Start Debugging Start Debugging Symbol symbol.

  • Enter the value 600 in the Subtotal TextBox:

  • Press the <ENTER> key on your keyboard or the Calculate Button button.

  • Repeat Subtotal values of 400, 200 and 50 to validate each of the test cases and percentages.

Below is the illustration for sample output with Subtotal input = 600:

Invoice Total Runtime 2

Figure VB-33: Visual Basic Invoice Total Form At Runtime with Subtotal = 600


Code Editor and Error List Windows with syntax errors displayed.

  • Visual Studio checks the syntax of your Visual Basic code as you enter it. if a syntax error occurs it is highlighted with a wavy underline in the code editor, and you can place the mouse pointer over it to display a description of the error.
  • If the Error List window is open, all of the build errors are listed in that window. Then, you can double-click on any error in the list to take you to its location in the Code Editor. When you correct the error, it is removed from the error list.
  • If the Error List window is closed, you can display it by selecting the Error List command from the View menu. Then, if you want to hide this window, you can click on its Auto-Hide button.
  • Visul Studio doesn't detect some errors until the project is built. As a result, you may encounter more syntax errors when you build and run the project.

Visual Basic Comments Description and Syntax

  • Comments: are used to help document what a progam does and what the code within it does.
  • Single-line Comment: Type // before the comment.
    • Use to add a comment as its own line or
    • Use to add a comment at the end of a line.

The Visual Basic Help Window

  • You can display a Help window be selecting an object in the Form Designer or positioning the insertion point in a keyword in the Code Editor and pressing F1.
  • You can also display a Help Window by selecting a command (such as Index, Contents or Search) from Visual Studio's Help menu.
  • The Help window works like a web browser and can display help topics that are available from your computer or from the Internet. You can use the buttons in its toolbar to navigate between help topics to your list of favorite topics.
  • The Help Window is divided into two panes. The left pane displays the Index, Content, and Help Favorites tabs that let you locate the help topics you want to display. The right pane displays each help topic in a separate window.
  • If you click on the Search button, the right pane will display a Search tab that lets you search for help topics by entering a word or phrase.
  • If you click on the How Do I button, the right pane will display a How Do I tab that lets you go to a topic by clicking on a link.
  • To close a tab, click on the Close button when the tab is active. To display a tab, click on the tab or select it from the Active Files drop-down list that's next to the Close button.

Visual Basic Language Essentials

At this point, we begin to delve into some details for coding Visual Basic statements. These will include coding arithmetic operations, selction and iteration statements, methods, data validation, arrays, collections dates and strings.

Visual Basic Built-In Data Types

Visual Basic Keyword Bytes .NET Type Description
Byte 1 Byte A positive integer value form 0 to 255
Sbyte 1 SBtye A signed integer value form -128 to 127
Short 2 Int16 An integer from -32,768 to +32,767
Ushort 2 UInt16 An unsigned integer fromm 0 to 65,535
Integer 4 Int32 An integer from -2,147,438,648 to +2,147,483,647
UInteger 4 UInt32 An unsigned integer from 0 to 4,294,967,295
Long 8 Int64 An integer from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong 8 UInt64 An unsigned integer from 0 to +18,446,744,073,709,551,615
Float 4 Single 3.402823E38 to 1.401298E45 for negative values;
1.401298E45 to 3.402823E38 for positive values
Double 8 Double 1.79769313486232E308 to 4.94065645841247E-324 for negative values;
4.94065645841247E324 to 1.79769313486232E308 for positive values
Decimal 16 Decimal 0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal;
smallest nonzero number is +/-0.0000000000000000000000000001 (+/-1E-28).
Char 2 Char A single Unicode character
Boolean 1 Boolean A true or false value
String variable String 1 to approx 2 billion Unicode characters

Figure VB-34: Visual Basic Built-In Data Types


Summary

  • The built-in data types are actually aliases for the data types defined by the Common Type System of the .NET Framework
  • All of the data types shown in this figure are value types, which means that they store their own data. In contrast, reference types store a reference to the area of memory where the data is stored.
  • A bit is a binary digit that can have a value of one or zero. A byte is a group of 8 bits. As a result, the number of bits for each data type is the number of bytes multiplied by 8.
  • Integers are whole numbers, and the first 8 data types above provide for signed and unsigned integers of various sizes.
  • Since the Decimal type is the most accurate non-integer data type, it is typically used to store monetary values.
  • The Unicode character set provides for over 65,000 characters, with two bytes used for each character. Each character maps to an integer value.
  • The older ASCII character set that's used by most operating systems provides for 256 characters with one byte used for each character. In the Unicode character set, the first 256 characters correspond to the 256 ASCII characters.
  • A Boolean data type stores a Boolean value that is either true or false.

Help Support this site


Thank you


Become a consultant
Many jobs available