VB Net Introduction Visual Studio 2012 Demo Start

VB. Net Introduction

Visual Studio 2012 Demo • Start page: New project/ Open project/Recent projects • Starting project: • File/New Project/ – C# /VB/Other language – Windows » Windows form application – Project name/Project folder • Project windows: – Form design view/Form code view – Solution Explorer • View/Solution Explorer – Tool. Box – Property Window • Properties and Events – Server Explorer – Project/Add New Item – Property window example

Introduction to Visual Basic. Net • Event-driven programming – The interface for a VB program consists of one or more forms, containing one or more controls (screen objects). – Form and controls have events that can respond to. Typical events include clicking a mouse button, type a character on the keyboard, changing a value, etc. – Event procedure

Form • Properties: – Name, Form. Border. Style, Text, Back. Color, Back. Image, Opacity • Events: – Load, Form. Closing, Form. Closed – Got. Focus, Lost. Focus – Mouse. Hover, Click, Double. CLick

Common VB. Net Controls • • Text. Box Label Button Check. Box Radio. Button List. Box Combo. Box Picture. Box

Text Box • Properties: – Auto. Size, Border. Style, Cause. Validation, Enabled, Locked, Multiline, Password. Char, Read. Only, Scroll. Bar, Tab. Index, Text, Visible, Word. Wrap, etc. • Properties can be set at the design time or at the run time using code. • To refer to a property: – Control. Name. Property. Name – Ex. Text. Box 1. Text – Note: The Text property is a string data type and automatically inherits the properties and methods of the string data type.

Typical VB. Net Programming Tasks • Creating the GUI elements that make up the application’s user interface. – Visualize the application. – Make a list of the controls needed. • Setting the properties of the GUI elements • Writing procedures that respond to events and perform other operations.

To Add an Event-Procedure • 1. Select the Properties window • 2. Click Events button • 3. Select the event and double-click it. • Note: Every control has a default event. • Form: Load event • Button control: Click event • Textbox: Text Changed event – To add the default event procedure, simply double -click the control.

Demo First. Name Last. Name Full. Name. Control properties. Event: Click, Mouse. Move, Form Load, etc. . Event procedures Full. Name: text. Box 3. Text = text. Box 1. Text + " " + text. Box 2. Text Demo: Text alignment (Text. Box 3. Text. Align=Horizontal. Align. Center) Text. Box 3. Back. Color=Color. Aqua

Demo Num 1 Num 2 Sum =. Control properties. Event: Click, Mouse. Move, Form Load, etc. . Event procedures Sum: text. Box 3. text=CStr(CDbl(text. Box 1. text)+CDbl(text. Box 2. text)) Or (CDbl(text. Box 1. text)+CDbl(text. Box 2. text)). to. String

Data Conversion Using VB Functions or. Net Methods • VB functions: Cstr, Cdbl, … • . Net framework: – System. Convert • Text. Box 3. Text = (System. Convert. To. Double(Text. Box 1. Text) + System. Convert. To. Double(Text. Box 2. Text)). To. String

Configure VB Project • Project property page – Application: • Target framework • Startup form – Compile: • Target CPU • Option: explicit, strict, compare – References • Tools/Options – Environment

VB Defaults • Option Explicit: – On --- must declare variables before use • Option Strict: – Off --- VB will convert the data (implicit conversion) • Option Compare: – Binary --- case sensitive – Text --- case insensitive • Option Infer – On --- When you set Option Infer to On, you can declare variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression.

Variable Declarations • Option Explicit • Dim variable. Name as Data. Type • Variable naming rules: – The first character must be a letter or an underscore character. – Use only letters, digits, and underscore. – Cannot contain spaces or periods. – No VB keywords • Naming conventions: – Descriptive – Consistent lower and upper case characters. • Ex. Camel casing: lower. Upper, employee. Name

Control Naming Conventions • The first three letters should be a lowercase prefix that indicates the control’s type. – frm, txt, lbl, btn. • The first letter after the prefix should be uppercase. – txt. Salary, lbl. Message • The part of the control name after the prefix should describe the control’s purpose in the application.

VB Data Types • • • Boolean (True/False): 2 bytes Byte: Holds a whole number from 0 to 255. Char: single character Date: date and time, 8 bytes. Decimal: Real number up to 29 significant digits, 16 bytes Double: real, 8 bytes Single: real, 4 bytes Integer: 4 bytes (int 32, uint 32) Long: 8 bytes integer Short: 2 bytes integer String Object: Holds a reference of an object

Variable Declaration Examples • Dim emp. Name as String • Declare multiple variables with one Dim: – Dim emp. Name, dependent. Name, emp. SSN as String • Dim X As Integer, Y As Single • Initiatialization – Dim interest. Rate as Double = 0. 0715

Variable Default Value • Variables with a numeric data type: 0 • Boolean variables: False • Date variables: 12: 00 AM, January 1 of the year 1. • String variables: Nothing

Arithmetic and String Operators • Arithmetic operators: +, -, *, /. ^ operator: Divides two numbers and returns an integer result. Mod: Divides two numbers and returns only the remainder. • Example: 10 mod 3 . Net Math class: Math. Pow(2, 3) • String Concatenation: &, + • Compound operator: : X= X+1 or X +=1

Example Dim dividend, divisor, quotient, remainder As Integer dividend = CInt(Text. Box 1. Text) divisor = CInt(Text. Box 2. Text) quotient = dividend divisor remainder = dividend Mod divisor Text. Box 3. Text = quotient Text. Box 4. Text = remainder

To. String • Message. Box. Show("quotient is: " + quotient) – Trigger error • Message. Box. Show("quotient is: " + quotient. To. String) • Message. Box. Show("Remainder is: " + remainder. To. String) • Option Strict

Change Machine to Return Smallest Number of Coins Dim changes, quarters, dimes, nickles, pennies As Integer changes = CInt(Text. Box 1. Text) quarters = changes 25 dimes = (changes - quarters * 25) 10 nickles = (changes - quarters * 25 - dimes * 10) 5 pennies = changes - quarters * 25 - dimes * 10 - nickles * 5 Text. Box 2. Text = quarters Text. Box 3. Text = dimes Text. Box 4. Text = nickles Text. Box 5. Text = pennies

FV = PV * (1 +Rate) Dim PV, Rate, Term, FV As Double PV = CDbl(Text. Box 1. Text) Rate = CDbl(Text. Box 2. Text) Term = CDbl(Text. Box 3. Text) FV = PV * (1 + Rate) ^ Term Text. Box 4. Text = FV. To. String("C") Year

Formatting Numbers with the To. String Method • The To. String method can optionally format a number to appear in a specific way • The following table lists the “format strings” and how they work with sample outputs Format String Description Number To. String() Result “N” or “n” Number format 12. 3 To. String(“n 3”) 12. 300 “F” or “f” Fixed-point scientific format 123456. 0 To. String("f 2") 123456. 00 “E” or “e” Exponential scientific format 123456. 0 To. String("e 3") 1. 235 e+005 “C” or “c” Currency format -1234567. 8 To. String("C") ($1, 234, 567. 80) “P” or “p” Percentage format . 234 To. String("P") 23. 40%

Data Conversion • Implicit conversion: When you assign a value of one data type to a variable of another data type, VB attempts to convert the value being assigned to the data type of the variable if the Option. Strict is set to Off. • Explicit conversion: – VB. Net Functions: CStr, Ccur, CDbl, Cint, CLng, CSng, Cdate, Val, etc. –. Net System. Convert • Type class’s methods: – to. String

Date Data Type • Variables of the Date data type can hold both a date and a time. The smallest value is midnight (00: 00) of Jan 1 of the year 1. The largest value is 11: 59 PM of Dec. 31 of the year 9999. • Date literals: A date literal may contain the date, the time, or both, and must be enclosed in # symbols: – #1/29/2013#, #1/31/2013 2: 10: 00 PM# – #6: 30 PM#, #18: 30: 00#

Date Examples • Date Literal Example: – Dim start. Date as date. Time – start. Date = #1/29/2013# • Use the System. Convert. To. Date. Time function to convert a string to a date value: – start. Date = System. Convert. To. Date. Time(“ 1/30/2003”) – If date string is entered in a text box: • start. Date = System. Convert. To. Date. Time(txt. Date. text) • Or start. Date=Cdate(txt. Date. text) • Date data type format methods: –. To. Long. Date. String, etc.

Some Date Functions • • • Now(): Current date and time Today(): Current date Time. Of. Day Date. Diff: Demo – Days between two dates – Days to Christmas • Date. Diff(Date. Interval. Day, Today(), #7/4/2013#) – Date data type properties and methods

Using Online Help • MSDN VB Developer Center – http: //msdn. microsoft. com/en-us/vstudio/hh 388573. aspx – Learn/Visual Basic language

The If … Then Statement • If condition Then Statements • End If • If condition Then Statements Else Statements • End If • Condition: – Simple condition: • Comparison of two expressions formed with relational operators: >, <, =, < >, >=, <= • Boolean variable – Complex condition: • Formed with logical operators: ( ), Not, And, Or

Example • State University calculates students tuition based on the following rules: – State residents: • Total units taken <=12, tuition = 1200 • Total units taken > 12, tuition = 1200 + 200 per additional unit. – Non residents: • Total units taken <= 9, tuition = 3000 • Total units taken > 9, tuition = 3000 + 500 per additional unit.

Decision Tree Units <= 12 or Not Resident or Not Units <= 9 or Not
![ELSEIF Statement • IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End ELSEIF Statement • IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End](http://slidetodoc.com/presentation_image_h/2bc49a28b118a809804e2450ca50de57/image-33.jpg)
ELSEIF Statement • IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End If
![Select Case Structure • SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END Select Case Structure • SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END](http://slidetodoc.com/presentation_image_h/2bc49a28b118a809804e2450ca50de57/image-34.jpg)
Select Case Structure • SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END SELECT

Select Case Example • SELECT CASE temperature CASE <40 Text. Box 1. text=“cold” CASE < 60 Text. Box 1. text=“cool” CASE 60 to 80 Text. Box 1. text=“warm” CASE ELSE Text. Box 1. text=“Hot” End Select

The Expression list can contain multiple expressions, separated by commas. Select Case number Case 1, 3, 5, 7, 9 text. Box 1. text=“Odd number” Case 2, 4, 6, 8, 10 text. Box 1. text=“Even number” Case Else End Select
![Loop • FOR index = start TO end [STEP step] [statements] [EXIT FOR] NEXT Loop • FOR index = start TO end [STEP step] [statements] [EXIT FOR] NEXT](http://slidetodoc.com/presentation_image_h/2bc49a28b118a809804e2450ca50de57/image-37.jpg)
Loop • FOR index = start TO end [STEP step] [statements] [EXIT FOR] NEXT index DO [{WHILE| UNTIL} condition] [statements] [EXIT DO] LOOP

Find the Sum of All Even Numbers between 1 and N Dim sum. Even, my. N, i As Integer my. N = CInt(Text. Box 1. Text) sum. Even = 0 For i = 1 To my. N If i Mod 2 = 0 Then sum. Even += i End If Next Message. Box. Show("The sum of even numbers is: " + sum. Even. To. String)

Do While sum. Even = 0 i=1 Do While i <= my. N If i Mod 2 = 0 Then sum. Even += i End If i += 1 Loop Message. Box. Show("The sum of even numbers is: " + sum. Even. To. String)

With … End With Convenient shorthand to execute a series of statements on a single object. Within the block, the reference to the object is implicit and need not be written. With Text. Box 1. Height = 250. Width = 600. Text = “Hello” End With

Function Private Function tax(salary) As Double tax = salary * 0. 1 End Function – Or Private Function tax(salary) As Double Return salary * 0. 1 End Function

Procedures . Sub procedure: Sub. Name(Arguments) … End Sub – To call a sub procedure SUB 1 CALL SUB 1(Argument 1, Argument 2, …) • Or SUB 1(Argument 1, Argument 2, …)

Call by Reference Call by Value • By. Ref – The address of the item is passed. Any changes made to the passing variable are made to the variable itself. • By. Val – Default – Only the variable’s value is passed.

By. Ref Example Private Sub Form 3_Load(sender As Object, e As Event. Args) Handles My. Base. Load Dim my. X, my. Y As Integer my. X = 10 test(my. X, my. Y) Message. Box. Show(my. Y) End Sub Private Sub test(x As Integer, By. Ref y As Integer) y=2*x End Sub

By. Ref, By. Val example Private Sub Button 1_Click(By. Val sender As System. Object, By. Val e As System. Event. Args) Handles Button 1. Click Dim my. Str As String my. Str = Text. Box 1. Text Call Change. Text. Ref (my. Str) Text. Box 1. Text = my. Str End Sub Private Sub Change. Text. Ref(By. Ref str. Input As String) str. Input = "New Text" End Sub

Variable Scope • Block-level scope: declared within a block of code terminated by an end, loop or next statement. – If city = “Rome” then • Dim message as string = “the city is in Italy” • Message. Box. Show(message) – End if • Procedural-level scope: declared in a procedure • Class-level, module-level scope: declared in a class or module but outside any procedure with either Dim or Private keyword. • Project-level scope: a module variable declared with the Public keyword.
- Slides: 46