vb.net introduction. visual studio 2012 demo start page: new project/ open project/recent projects...

46
VB.Net Introduction

Upload: william-henry

Post on 17-Jan-2018

226 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

VB.Net Introduction

Page 2: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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– ToolBox– Property Window

• Properties and Events– Server Explorer– Project/Add New Item– Property window example

Page 3: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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

Page 4: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Form

• Properties:– Name, FormBorderStyle, Text, BackColor,

BackImage, Opacity• Events:

– Load, FormClosing, FormClosed– GotFocus, LostFocus– MouseHover, Click, DoubleCLick

Page 5: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Common VB.Net Controls

• TextBox• Label• Button• CheckBox• RadioButton• ListBox• ComboBox• PictureBox

Page 6: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Text Box• Properties:

– AutoSize, BorderStyle, CauseValidation, Enabled, Locked, Multiline, PasswordChar, ReadOnly, ScrollBar, TabIndex, Text, Visible, WordWrap, etc.

• Properties can be set at the design time or at the run time using code.

• To refer to a property: – ControlName.PropertyName– Ex. TextBox1.Text– Note: The Text property is a string data type and

automatically inherits the properties and methods of the string data type.

Page 7: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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.

Page 8: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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.

Page 9: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Demo

FirstName

LastName

FullName

.Control properties

.Event: Click, MouseMove, Form Load, etc.

.Event proceduresFullName: textBox3.Text textBox3.Text = textBox1.Text + " " + textBox2.Text

Demo: Text alignment (TextBox3.TextAlign=HorizontalAlign.Center)TextBox3.BackColor=Color.Aqua

Page 10: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Demo

Num1

Num2

Sum =

.Control properties

.Event: Click, MouseMove, Form Load, etc.

.Event proceduresSum: textBox3.text=CStr(CDbl(textBox1.text)+CDbl(textBox2.text))Or (CDbl(textBox1.text)+CDbl(textBox2.text)).toString

Page 11: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Data Conversion Using VB Functions or .Net Methods

• VB functions: Cstr, Cdbl, …• .Net framework:

– System.Convert

• TextBox3.Text = (System.Convert.ToDouble(TextBox1.Text) + System.Convert.ToDouble(TextBox2.Text)).ToString

Page 12: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Configure VB Project• Project property page

– Application:• Target framework• Startup form

– Compile:• Target CPU• Option: explicit, strict, compare

– References• Tools/Options

– Environment

Page 13: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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.

Page 14: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Variable Declarations• Option Explicit• Dim variableName as DataType• 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: lowerUpper, employeeName

Page 15: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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.– txtSalary, lblMessage

• The part of the control name after the prefix should describe the control’s purpose in the application.

Page 16: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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 (int32, uint32)• Long: 8 bytes integer• Short: 2 bytes integer• String• Object: Holds a reference of an object

Page 17: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Variable Declaration Examples

• Dim empName as String• Declare multiple variables with one Dim:

– Dim empName, dependentName, empSSN as String • Dim X As Integer, Y As Single• Initiatialization

– Dim interestRate as Double = 0.0715

Page 18: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Variable Default Value

• Variables with a numeric data type: 0• Boolean variables: False• Date variables: 12:00:00 AM, January 1 of

the year 1.• String variables: Nothing

Page 19: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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

Page 20: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Example

Dim dividend, divisor, quotient, remainder As Integer dividend = CInt(TextBox1.Text) divisor = CInt(TextBox2.Text) quotient = dividend \ divisor remainder = dividend Mod divisor TextBox3.Text = quotient TextBox4.Text = remainder

Page 21: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

ToString

• MessageBox.Show("quotient is:" + quotient)– Trigger error

• MessageBox.Show("quotient is:" + quotient.ToString)• MessageBox.Show("Remainder is: " + remainder.ToString)• Option Strict

Page 22: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Change Machine to Return Smallest Number of Coins

Dim changes, quarters, dimes, nickles, pennies As Integer changes = CInt(TextBox1.Text) quarters = changes \ 25 dimes = (changes - quarters * 25) \ 10 nickles = (changes - quarters * 25 - dimes * 10) \ 5 pennies = changes - quarters * 25 - dimes * 10 - nickles * 5 TextBox2.Text = quarters TextBox3.Text = dimes TextBox4.Text = nickles TextBox5.Text = pennies

Page 23: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

FV = PV * (1 +Rate) Year

Dim PV, Rate, Term, FV As Double PV = CDbl(TextBox1.Text) Rate = CDbl(TextBox2.Text) Term = CDbl(TextBox3.Text) FV = PV * (1 + Rate) ^ Term TextBox4.Text = FV.ToString("C")

Page 24: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Formatting Numbers with the ToString Method

• The ToString 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 ToString() Result

“N” or “n” Number format 12.3 ToString(“n3”) 12.300

“F” or “f” Fixed-point scientific format 123456.0 ToString("f2") 123456.00

“E” or “e” Exponential scientific format 123456.0 ToString("e3") 1.235e+005

“C” or “c” Currency format -1234567.8 ToString("C") ($1,234,567.80)

“P” or “p” Percentage format .234 ToString("P") 23.40%

Page 25: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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 OptionStrict 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:– toString

Page 26: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Date Data Type

• Variables of the Date data type can hold both a date and a time. The smallest value is midnight (00:00:00) of Jan 1 of the year 1. The largest value is 11:59: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#

Page 27: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Date Examples• Date Literal Example:

– Dim startDate as dateTime– startDate = #1/29/2013#

• Use the System.Convert.ToDateTime function to convert a string to a date value:– startDate = System.Convert.ToDateTime(“1/30/2003”)– If date string is entered in a text box:

• startDate = System.Convert.ToDateTime(txtDate.text)• Or startDate=Cdate(txtDate.text)

• Date data type format methods:– .ToLongDateString, etc.

Page 28: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Some Date Functions

• Now(): Current date and time• Today(): Current date• TimeOfDay• DateDiff:• Demo

– Days between two dates– Days to Christmas

• DateDiff(DateInterval.Day, Today(), #7/4/2013#)– Date data type properties and methods

Page 29: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Using Online Help

• MSDN VB Developer Center– http://msdn.microsoft.com/en-us/vstudio/hh388573.aspx– Learn/Visual Basic language

Page 30: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

The If … Then Statement• If condition Then

Statements• End If• If condition Then

StatementsElse

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

Page 31: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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.

Page 32: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Decision Tree

Resident or Not

Units <= 12 or Not

Units <= 9 or Not

Page 33: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

ELSEIF Statement

• IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End If

Page 34: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Select Case Structure

• SELECT CASE testexpression[CASE expressionlist-n

[Statements][CASE ELSE

[elsestatements]END SELECT

Page 35: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Select Case Example• SELECT CASE temperature

CASE <40TextBox1.text=“cold”

CASE < 60TextBox1.text=“cool”

CASE 60 to 80TextBox1.text=“warm”

CASE ELSETextBox1.text=“Hot”

End Select

Page 36: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

The Expression list can contain multiple expressions, separated by commas.Select Case number

Case 1, 3, 5, 7, 9textBox1.text=“Odd number”

Case 2, 4, 6, 8, 10textBox1.text=“Even number”

Case ElseEnd Select

Page 37: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Loop

• FOR index = start TO end [STEP step][statements][EXIT FOR]NEXT indexDO [{WHILE| UNTIL} condition][statements][EXIT DO]LOOP

Page 38: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Find the Sum of All Even Numbers between 1 and N

Dim sumEven, myN, i As Integer myN = CInt(TextBox1.Text) sumEven = 0 For i = 1 To myN If i Mod 2 = 0 Then sumEven += i End If Next MessageBox.Show("The sum of even numbers is: " + sumEven.ToString)

Page 39: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Do While

sumEven = 0i = 1Do While i <= myN If i Mod 2 = 0 Then sumEven += i End If i += 1LoopMessageBox.Show("The sum of even numbers is: " + sumEven.ToString)

Page 40: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

With … End With

With TextBox1

.Height = 250

.Width = 600

.Text = “Hello”

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.

Page 41: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Function

Private Function tax(salary) As Doubletax = salary * 0.1

End Function– Or

Private Function tax(salary) As DoubleReturn salary * 0.1

End Function

Page 42: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Procedures. Sub procedure:

Sub SubName(Arguments)…

End Sub– To call a sub procedure SUB1

CALL SUB1(Argument1, Argument2, …) •OrSUB1(Argument1, Argument2, …)

Page 43: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

Call by Reference Call by Value

• ByRef– The address of the item is passed. Any changes

made to the passing variable are made to the variable itself.

• ByVal– Default– Only the variable’s value is passed.

Page 44: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

ByRef Example

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim myX, myY As Integer myX = 10 test(myX, myY) MessageBox.Show(myY) End Sub Private Sub test(x As Integer, ByRef y As Integer) y = 2 * x End Sub

Page 45: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

ByRef, ByVal examplePrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim myStr As String

myStr = TextBox1.Text

Call ChangeTextRef (myStr)

TextBox1.Text = myStr

End Sub

Private Sub ChangeTextRef(ByRef strInput As String)

strInput = "New Text"

End Sub

Page 46: VB.Net Introduction. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# /VB/Other language

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”• MessageBox.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.