Visual Basic.NET Programming January 21, 2004

Download Report

Transcript Visual Basic.NET Programming January 21, 2004

Visual Basic.NET Programming
January 21, 2004
Class Agenda – January 21, 2004
Homework
Open Questions?
Programming Paradigm's
Program Design Tools
Review Homework Assignment
Modular Programming
Visual Basic.NET Language Features
Class ExerciseWrite a Modular Name Lister
Introduction to Windows Forms
Homework
1. Zip entire project
2. Email zip file to me
3. I will acknowledge receipt of homework,
probably something as simple as "got it"
4. I tend to send out grades after all
assignments are in...
5. If you really want to know send me an
email and I'll make a special effort
Questions?
• Concatenation Operators
Concatenation Operators
• & Operator
result = expression1 & expression2
• + Operator
expression1 + expression2
& Operator
result = expression1 & expression2
• Generates a string concatenation of two
expressions.
• If the data type of expression1 or expression2 is not
String but widens to String, it is converted to
String. If one of the data types does not widen to
String, the compiler generates an error.
• The data type of result is String. If one or both
expressions are stated as Nothing or have a value
of DBNull.value, they are treated as a string with a
value of "".
+ Concatenation Operator
expression1 + expression2
• Adds two numbers. Also used to concatenate two
strings.
• The value of the result will be the sum of
expression1 and expression2 if expression1 and
expression2 are numeric or the result of the
concatenation of expression1 and expression2 if
expression1 and expression2 are strings.
C# String Concatenation
• The binary + operator performs string
concatenation when one or both operands are of
type string.
• If an operand of string concatenation is null, an
empty string is substituted.
• Otherwise, any non-string argument is converted
to its string representation by invoking the virtual
ToString method inherited from type object. If
ToString returns null, an empty string is
substituted.
Programming Paradigm's
Programming Paradigms
• Procedural Programming  Console Applications
(Sequential Flow)
• Procedural Programming (Modular Design)
• Event Driven Programming  Windows Forms
Applications (Random Flow)
• Object Oriented Programming  Combining Data
and Procedures into Standalone Components.
Procedural Programming
• Console Applications
• Programs have a sequential flow
• Programmer can anticipate and control
logical flow
• Typical
–
–
–
–
Open a File
Read through a file one record at a time
Process each record
At End Close File
Event Driven Programming
• Windows Applications
• Web Form Applications
• Programs do NOT have a predictable flow to them,
but respond to user input (point and click)
• Getting input out of sequence is a design
consideration
• Typical
– User selects a menu item
– User opens a second file and switches between files
– User inserts or removes data randomly
Object Oriented Programming
• Combining Data and Procedures into
Standalone Components.
• Have to wait a couple of weeks...
Program Design Tools
How To Design a Program
• Pseudocode
• Using a Flow Chart
Pseudocode
• Informal language to helps programmers
develop algorithms
• Not executed on computers
• Helps conceptualize a program during the
program-design process
• Describes only executable statements
Name Lister Pseudo Code Example
Enter First Name (if empty  error, try again)
Enter Middle Name
Enter Last Name (if empty  error, try again)
Concatinate Name Fields  build full name
Check Length (if > 20 then shorten full name)
Request display type (horizontal or vertical,
forward or backward)  display accordingly
7. add loops (another display? another name? exit
logic...)
1.
2.
3.
4.
5.
6.
Flow Charting
• Flowcharts
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols
•
•
•
•
Rectangles
Diamonds
Ovals
Small circles
Flowcharting Visual Basic’s sequence
structure.
add grade to total
total = total + grade
add 1 to counter
counter = counter + 1
Flowcharting a single-selection If/Then
structure.
Grade >= 60
false
true
Console.WriteLine(“Passed”)
Flowcharting a double-selection
If/Then/Else structure
Console.WriteLine(“Failed”)
false
Grade >= 60
true
Console.WriteLine(“Passed”)
So, how do we design programs?
Let's look at the Homework
Assignment
Name Lister Console Application
•
•
Sequential Flow (Procedural Programming)
List Steps
–
–
–
–
–
–
–
Enter First Name (if empty  error, try again)
Enter Middle Name
Enter Last Name (if empty  error, try again)
Concatinate Name Fields  build full name
Check Length (if > 20 then shorten full name)
Request display type (horizontal or vertical, forward or
backward)  display accordingly
add loops (another display? another name? exit logic...)
Sequential Name Lister
Code Walkthrough
Modular Programming
Modular Programming
• Modules, Sub Procedures and Functions
• Value Types and Reference Types
• Concept of Scope
Introduction
• Divide and Conquer
– The best way to develop and maintain a large
program is to construct it from small,
manageable pieces.
Modules, Sub Procedures and
Functions
• Division of code into procedures
– Several motivations to divide code into procedures
• Divide-and-conquer approach makes program
development more manageable
• Used to group related procedures so that they can be
reused in other projects
• Software reusability between programs
• Avoids the repetition of code in a program
• Should be self-contained
Modules, Sub Procedures and
Functions
Boss
Worker1
Worker4
Worker2
Worker3
Worker5
Hierarchical boss procedure/worker procedure relationship.
Functions and Sub Procedures
• Provide the ability to transfer control within a program.
• Simplify code sharing, providing an excellent way to
eliminate redundant code.
• Maybe called with one or more arguments or with no
arguments at all
Sub Procedures
• Format of a procedure definition
Sub procedure-name(parameter-list)
declarations and statements
End Sub
• Procedure header
– The first line is known as the procedure header
• Procedure-name
– Directly follows the Sub keyword
– Can be any valid identifier
– It is used to call this Sub procedure within the program
• Procedure body
– The declarations and statements in the procedure definition form
the procedure body
Function Procedures
• Similar to Sub procedures
• One important difference
– Function procedures return a value to the
caller
Function Procedures
• Format of a Function procedure definition
Function procedure-name(parameter-list) As return-type
declarations and statements
End Function
• Return-type
– Indicates the data type of the result returned from the
Function to its caller
• Return expression
– Can occur anywhere in a Function
– It returns exactly one value
– Control returns immediately to the point at which that procedure
was invoked
Subroutines with Arguments
Sub AnyProcedure(ByRef strTmp as String)
AnyProcedure(“hi there”)
Sub AnyProcedure(ByRef strTmp As String,
ByRef iTmp As Integer)
AnyProcedure(“hi there”, 4)
Subroutines with Arguments
(continued)
Sub AnyProcedure(ByRef strTmp As String,
ByVal iTmp As Integer)
Dim strTmp As String = “Hello World”
Dim iTmp As Integer = 14
AnyProcedure(strTmp, iTmp)
Functions with Arguments
Sub AnyProcedure(ByRef strTmp as String) As
String
Dim aString As String
aString = AnyProcedure(“hi there”)
Function AnyProcedure(ByRef strTmp As String,
ByRef iTmp As Integer) As String
aString = AnyProcedure(“hi there”, 4)
Function with Arguments (continued)
Function AnyProcedure(ByRef strTmp As String,
ByVal iTmp As Integer) As String
Dim strTmp As String = “Hello World”
Dim iTmp As Integer = 14
Dim aString As String
aString = AnyProcedure(strTmp, iTmp)
Value Types and Reference Types
Value Types and Reference Types
• A data type is a value type if it holds the data within its own
memory allocation. A reference type contains a pointer to another
memory location that holds the data.
• Value types include:
– All numeric data types
– Boolean, Char, and Date
– All structures, even if their members are reference types
– Enumerations, since their underlying type is always Byte,
Short, Integer, or Long
• Reference types include:
– String
– All arrays, even if their elements are value types
– Class types, such as Form
Passing Arguments
Pass-by-Value vs. Pass-by-Reference
• Pass-by-value
– The program makes a copy of the argument’s
value and passes that copy to the called
procedure
• Pass-by-reference
– The caller gives the called procedure the ability
to access and modify the caller’s original data
directly.
Argument Passing ByVal
• If you pass a variable argument by value using the ByVal
keyword, the procedure cannot modify the variable itself.
• If the argument is a reference type, you can modify the
members of the object to which it points, even though you
cannot replace the object itself.
• You can modify the members of the object.
• If the argument is an array variable, you cannot assign a
new array to it, but you can change one or more of its
elements. The changed elements are reflected in the
underlying array variable in the calling code.
Argument Passing ByRef
• If you pass a variable argument by reference
using the ByRef keyword, the procedure can
modify the variable itself.
• If the argument is an object variable, you can
assign a new object to it. This reassignment also
affects the object variable in the calling program.
Concept of Scope
Scope
When a variable is defined (i.e. as in a Dim
statement) the computer assigns memory to
that variable. When the variable is no longer
needed the computer deletes the variable to
free up the memory. Scope defines the time a
variable is available to a program.
Scope
A variable defined in a Subroutine or in For Next
statement will be deleted when the Subroutine or
For Next statement is exited.
Variables that need to persist longer than the life of
the Subroutine need to be defined outside the
Subroutine, at least at the class or module level.
Scope Rules
• Possible scopes
– Module scope
• Variable declared in a module have module scope, which is
similar to class scope
– Namespace scope
• Procedures defined in a module have namespace scope,
which generally means that they may be accessed throughout
a project
– Block scope
• Identifiers declared inside a block, such as the body of a
procedure definition or the body of an If/Then selection
structure, have block scope
– Class scope
• Begins at the class identifier after keyword Class and
terminates at the End Class statement
Visual Basic.NET Language Features
Visual Basic.NET Language Features
•
•
•
•
•
•
•
Review Data Types
Logical Operators
Control Structures
Assignment Operators
Exit Statement
Print and Display Constants
MessageBox Class
Visual Basic.NET Keywords
AddHandler
AddressOf
Alias
And
AndAlso
Ansi
As
Assembly
Auto
Boolean
ByRef
Byte
ByVal
Call
Case
Catch
CBool
CByte
CChar
CDate
CDec
CDbl
Char
CInt
Class
CLng
CObj
Const
CShort
CSng
CStr
CType
Date
Decimal
Declare
Default
Delegate
Dim
Do
Double
Each
Else
ElseIf
End
Enum
Erase
Error
Event
Exit
ExternalSource
False
Finally
For
Friend
Function
Get
GetType
GoTo
Handles
If
Implements
Imports
In
Inherits
Integer
Interface
Is
Lib
Like
Long
Loop
Me
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
New
Next
Not
Nothing
NotInheritable
NotOverridable
Object
On
Option
Optional
Or
OrElse
Overloads
Overridable
Overrides
ParamArray
Preserve
More Visual Basic.NET Keywords
Private
RaiseEvent
Rem
Select
Short
Stop
SyncLock
True
Until
WithEvents
#If...Then...#Else
Property
ReadOnly
RemoveHandler
Set
Single
String
Then
Try
When
WriteOnly
-
Protected
ReDim
Resume
Shadows
Static
Structure
Throw
TypeOf
While
Xor
-=
Public
Region
Return
Shared
Step
Sub
To
Unicode
With
#Const
&
&=
*
*=
/
/=
\
\=
^
^=
+
+=
=
The following are retained as keywords, although they are no longer supported in Visual
Basic.NET
Let
Variant
Wend
Revisit Data Types
• Integers
– Int16 (Short)
– Int32
– Int64 (Long)
• Boolean
• Floating Point
– Single Word (32 bit)
– Double Word (64 bit)
• Char and Byte
• Decimal
• String
Integer Data Types
Integer variables are stored as signed 32-bit (4-byte) integers
ranging in value from -2,147,483,648 through 2,147,483,647.
The Integer data type provides optimal performance on a 32-bit
processor, as the smaller integral types are slower to load and store
from and to memory. (Int32)
Short variables are stored as signed 16-bit (2-byte) integers ranging
in value from -32,768 through 32,767. (Int16)
Long variables are stored as signed 64-bit (8-byte) integers ranging
in value from -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807. (Int64)
Boolean
Dim bTmp As Boolean
bTmp = True
Dim bTmp As Boolean = False
Boolean variables are stored as 16-bit (2-byte)
numbers, but they can only be True or False. Use
the keywords True and False to assign one of the
two states to Boolean variables.
Floating Point Data Types
Single variables are stored as signed IEEE 32-bit (4-byte)
single-precision floating-point numbers ranging in value from 3.4028235E+38 through -1.401298E-45 for negative values and
from 1.401298E-45 through 3.4028235E+38 for positive
values. Single-precision numbers store an approximation of a
real number.
Double variables are stored as signed IEEE 64-bit (8-byte)
double-precision floating-point numbers ranging in value from
-1.79769313486231570E+308 through 4.94065645841246544E-324 for negative values and from
4.94065645841246544E-324 through
1.79769313486231570E+308 for positive values.
Char and Byte Data Types
•Char - Char variables are stored as unsigned 16-bit (2byte) numbers ranging in value from 0 through 65535. Each
number represents a single Unicode character. Direct
conversions between the Char data type and the numeric
types are not possible, but you can use the AscW and
ChrW functions for this purpose.
•Byte - Byte variables are stored as unsigned 8-bit (1-byte)
numbers ranging in value from 0 through 255.
Decimal Data Type
Decimal variables are stored as signed 128-bit (16-byte) integers scaled by a variable
power of 10. The scaling factor specifies the number of digits to the right of the decimal
point; it ranges from 0 through 28. With a scale of 0 (no decimal places), the largest
possible value is +/-79,228,162,514,264,337,593,543,950,335. With 28 decimal places,
the largest value is +/-7.9228162514264337593543950335, and the smallest nonzero
value is +/-0.0000000000000000000000000001 (+/-1E-28).
Appending the literal type character D to a literal forces it to the Decimal data type.
Appending the identifier type character @ to any identifier forces it to Decimal. You
might need to use the D type character to assign a large value to a Decimal variable or
constant, as the following example shows:
Dim BigDec1 As Decimal = 9223372036854775807 ' No overflow.
Dim BigDec2 As Decimal = 9223372036854775808 ' Overflow.
Dim BigDec3 As Decimal = 9223372036854775808D ' No overflow.
This is because without a literal type character the literal is taken as Long, and the
value to be assigned to BigDec2 is too large for the Long type.
Logical Operators
Logical Operators
• Used to form complex conditions by combining
simple ones
– Short-circuit evaluation
• Execute only until truth or falsity is known
– AndAlso operator
• Returns true if and only if both conditions are true
– OrElse operator
• Returns true if either or both of two conditions are true
Logical Operators without short-circuit
evaluation
• And and Or
– Similar to AndAlso and OrElse respectively
– Always execute both of their operands
– Used when an operand has a side effect
• Condition makes a modification to a variable
• Should be avoided to reduce subtle errors
• Xor
– Returns true if and only if one operand is true and the
other false
Logical Negation
Not
– Used to reverse the meaning of a condition
– Unary operator
• Requires one operand
– Can usually be avoided by expressing a
condition differently
AndAlso Logical Operator
expression1
expression2
False
False
expression1 AndAlso
expression2
False
False
True
True
True
False
True
False
False
True
OrElse Logical Operator
expression1
False
expression2
False
expression1 OrElse expression2
False
False
True
True
True
False
True
True
True
True
Xor Logical Operator
expression1
expression2
False
False
expression1 Xor
expression2
False
False
True
True
True
False
True
True
True
False
Not Logical Operator
expression
False
Not expression
True
True
False
Precedence and associativity of the
operators discussed so far.
Operators
()
Associativity
left to right
Type
parentheses
^
+*/
\
Mod
+&
< <= > >= = <>
Not
And AndAlso
Or OrElse
Xor
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
exponentiation
unary prefix
multiplicative
Integer division
modulus
additive
concatenation
relational and equality
logical NOT
boolean logical AND
boolean logical inclusive OR
boolean logical exclusive OR
Rules of Precedence
•
There are 18 (or 13?) Rules of Precedence
which can actually be reduced to 2.
1. Multiply / Divide before you Add /
Subtract
2. Put ()'s around everything
Control Structures
Control Structures
• Transfer of control
• Selection Structures
• Repetition Structures
Transfer of control
• GoTo statement
It causes programs to become quite unstructured
and hard to follow.
Selection Structures
• If/Then
– Single-selection structure
• If/Then/Else
– Double-selection structure
• If/ElseIf/ElseIf.../Else
– Multiple-selection structure
• Select Case
– Multiple-selection structure
Select Case Statements
• More Elegant Than the If Else Construct
• Begin with the words Select Case followed by the
name of the target variable
• For each value or range of values for the target
variable a separate case in listed.
• Each case begins with the word Case followed by
a specific value or range of values for that case.
• Following each Case statement is one of more
lines of code to be executed if that case is true.
• An Else Case is often provided to catch any cases
that do not match the target variable.
• End with the words End Select
Case Statement Syntax
Dim strTmp As String
'….
Select Case strTmp
Case “add”
some code
Case “delete”
some code
Else Case
perhaps an error message
End Select
Case Statement
Dim Number As Integer = 8
' ...
Select Case Number ' Evaluate Number.
Case 1 To 5 ' Number between 1 and 5, inclusive.
Debug.WriteLine("Between 1 and 5")
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8 ' Number between 6 and 8.
Debug.WriteLine("Between 6 and 8")
Case 9 To 10 ' Number is 9 or 10.
Debug.WriteLine("Greater than 8")
Case Else ' Other values.
Debug.WriteLine("Not between 1 and 10")
End Select
Repetition Structures
•
•
•
•
•
•
•
For/Next
For Each/Next
While
Do While/Loop
Do/Loop While
Do Until/Loop
Do/Loop Until
Essentials of Counter-Controlled
Repetition
• Elements needed
– Control variable
• Used to determine whether loop continues to iterate
– Initial value of control variable
– Increment (or decrement)
• Describes how control variable is modified during each
iteration
– Condition
• Tests for final value of control variable
For/Next Counter-Controlled
Repetition
• Structure header initializes control variable, specifies final value
and increment
– For keyword begins structure
• Followed by control variable initialization
– To keyword specifies final value
– Step keyword specifies increment
• Optional
• Increment defaults to 1 if omitted
• May be positive or negative
• Next keyword marks end of structure
• Executes until control variable greater (or less) than final value
For/Next Repetition Structure
For
keyword
Initial value of
control variable
Final value of
control
variable
Increment of control
variable
For counter = 2 To 10 Step 2
Control variable
name
To
keyword
Step
keyword
While...End While Statements
• Executes a series of statements as long as a given condition is True.
While condition
[ statements ]
End While
• If condition is True, all of the statements are executed until the End
While statement is encountered. Control then returns to the While
statement and condition is again checked. If condition is still True,
the process is repeated.
• If condition is False, execution resumes with the statement
following the End While statement.
• You can nest While loops by placing one loop within another.
Assignment Operators
Assignment Operators
• Binary operators
– +, -, *, ^, &, / or \
variable = variable operator expression
variable operator= expression
• Example
– Addition assignment operator, +=
value = value + 3
value += 3
Assignment Operators
Assignment
operator
Assume: c = 4, d =
"He"
+=
-=
*=
/=
\=
^=
&=
Sample
expression
Explanation
Assigns
c += 7
c -= 3
c *= 4
c /= 2
c \= 3
c ^= 2
d &= "llo"
c=c+7
c=c-3
c=c*4
c=c/2
c=c\3
c=c^2
d = d & "llo"
11 to c
1 to c
16 to c
2 to c
1 to c
16 to c
"Hello" to d
Exit Statement
Using the Exit Keyword in a Repetition
Structure
• Exit Statements
– Alter the flow of control
• Cause immediate exit from a repetition structure
– Exit Do
• Executed in Do structures
– Exit For
• Executed in For structures
– Exit While
• Executed in While structures
Print and Display Constants
Print and Display Constants
Member
Constant
Equivalent
Description
CrLf
vbCrLf
Chr(13) + Chr(10)
Carriage return/linefeed character
combination.
Cr
vbCr
Chr(13)
Carriage return character.
Lf
vbLf
Chr(10)
Linefeed character.
NewLine
vbNewLine
Chr(13) + Chr(10)
New line character.
NullChar
vbNullChar
Chr(0)
Character having value 0.
na
vbNullString
String having value 0
Not the same as a zero-length string ("");
used for calling external procedures.
na
vbObjectError
-2147221504
Error number. User-defined error
numbers should be greater than this
value. For example:
Tab
vbTab
Chr(9)
Err.Raise(Number) = vbObjectError
+
Tab1000
character.
Back
vbBack
Chr(8)
Backspace character.
FormFeed
vbFormFeed
Chr(12)
Not useful in Microsoft Windows.
VerticalTab
vbVerticalTab
Chr(11)
Not useful in Microsoft Windows.
Quote
na
Chr(34)
Quotation mark character (" or ') used to
enclose values.
MessageBox
MessageBox Class
Displays a Dialog box that can contain text,
buttons, and symbols to inform and instruct the
user.
MessageBox.Show Method (String, String,
MessageBoxButtons, MessageBoxIcon)
Displays a message box with specified text, caption, buttons, and icon.
MessageBox.Show(text As String, caption As String, buttons As
MessageBoxButtons, icon As MessageBoxIcon) As
DialogResult
Parameters
text - The text to display in the message box.
caption - The text to display in the title bar of the message box.
buttons - One of the MessageBoxButtons values that
specifies
which buttons to display in the message box.
icon - One of the MessageBoxIcon values that specifies
which
icon to display in the message box.
Return Value
One of the DialogResult values.
MessageBox Buttons
MessageBoxButton constants
MessageBoxButton.OK
Description
OK button. Allows the user to acknowledge a
message. Included by default.
MessageBoxButton.OKCancel
OK and Cancel buttons. Allow the user to
either continue or cancel an operation.
MessageBoxButton.YesNo
Yes and No buttons. Allow the user to respond
to a question
MessageBoxButton.YesNoCancel
Yes, No and Cancel buttons. Allow the user to
respond to a question or cancel an operation.
MessageBoxButton.RetryCancel
Retry and Cancel buttons. Typically used to
allow the user to either retry or cancel an
operation that has failed.
MessageBoxButton.AbortRetry-
Abort, Retry and Ignore buttons. When one
of a series of operations has failed, these butons
allow the user to abort the entire sequence, retry
the failed operation or ignore the failed
operation and continue..
Ignore
MessageBox Icons
MessageBoxIcon Constants
MessageBoxIcon.Exclamation
Icon
Description
Icon containing an exclamation point.
Typically used to caution the user
against potential problems.
MessageBoxIcon.Information
Icon containing the letter "i." Typically
used to display information about the
state of the application.
MessageBoxIcon.Question
Icon containing a question mark.
Typically used to ask the user a
question.
Icon containing an in a red circle.
Typically used to alert the user of
errors or critical situations.
MessageBoxIcon.Error
Dialog Result - Specifies identifiers to indicate the
return value of a dialog box.
Abort - The return value is Abort (usually sent from a button labeled Abort).
Cancel - The return value is Cancel (usually sent from a button labeled Cancel).
Ignore - The return value is Ignore (usually sent from a button labeled Ignore).
No - The return value is No (usually sent from a button labeled No).
None - Nothing is returned from the dialog box. This means that the modal dialog
continues running.
OK - The return value is OK (usually sent from a button labeled OK).
Retry - The return value is Retry (usually sent from a button labeled Retry).
Yes - The return value is Yes (usually sent from a button labeled Yes).
MessageBox Sample Code
Dim strMessage As String = "No server name. Cancel
operation?"
Dim strCaption As String = "No Server Name Specified"
Dim iBttns As Integer = MessageBoxButtons.YesNo
Dim iIcon As Integer = MessageBoxIcon.Question
Dim Result As DialogResult
'Displays a MessageBox using the Question icon and specifying
the No
button as the default.
Result = MessageBox.Show(strMessage, strCaption, iBttns ,
iIcon)
' Gets the result of the MessageBox display.
If Result = DialogResult.Yes Then
Me.Close() ' Closes the parent form.
End If
Class Exercise
Write a Modular Name Lister
Application
Name Lister Modular Code
• Transition from a Sequential to a Modular Design
Structure
• Console or Windows Form if your adventurous!
• Remove GoTo Statements
• Add Functions and Subroutines
• Use While  End While blocks
• Add a Select Case statement
• Use a MessageBox for errors plus the two loop
questions (another display? and another name?)
Introduction to Windows Forms
Introduction to Windows Forms
•
•
•
•
•
Windows Form
Using ToolBox to add Controls to Form
Label Control
Button
Using F1 or Search for Help
What Are Controls?
• Controls are things like TextBoxes, Buttons,
and Labels that you use to build a form.
• When you create Windows Form project the
IDE provides a blank form.
• Controls are added to the form to provide
functionality
What are properties?
•
•
•
•
•
•
Forms Have Properties
Controls Have Properties
Properties are used to specify controls.
Text Boxes have Font properties
Fonts have size and color and bold and …
Labels have a Text property to describe the
label
What About Events?
• When you click on a button the IDE
automatically creates a method where you
can write the code you wish executed when
the button is pushed. This event is called an
On_Click event.
Windows Form
A Couple of Properties
• ActiveForm  points to current form
• BackColor Property  sets background color
To set a BackColor:
ActiveForm.BackColor = Color.Red
To Test For a BackColor:
ActiveForm.BackColor.Equals(Color.Red)
Windows Controls
Windows Controls
•
•
•
•
•
Label Control
Button Control
RadioButton Control
GroupBox Control
ComboBox Control
Using ToolBox to add Controls to Form
• Showing the ToolBox
• Selecting a Control
• Configuring the Control
Label Control
Windows Forms Label controls are used to display
text or images that cannot be edited by the user, but
can be edited dynamically by the programmer.
–BackColor defaults to Form
–ForeColor
Label1.ForeColor = Color.White
Note: Font changes must be made directly to
the control on the form.
Button Control
The Windows Forms Button control allows
the user to click it to perform an action.
Button1.Text = “Push Me”
Button1.BackColor = Color.Blue
Button1.ForeColor = Color.Yellow
RadioButton Control
Windows Forms RadioButton controls present a set of two or more mutually
exclusive choices to the user. While radio buttons and check boxes may appear to
function similarly, there is an important difference: when a user selects a radio
button, the other radio buttons in the same group cannot be selected as well. In
contrast, any number of check boxes can be selected. Defining a radio button group
tells the user, "Here is a set of choices from which you can choose one and only
one."
When a RadioButton control is clicked, its Checked property is set to true and the
Click event handler is called. The CheckedChanged event is raised when the value
of the Checked property changes. If the AutoCheck property is set to true (the
default), when the radio button is selected all others in the group are automatically
cleared. This property is usually only set to false when validation code is used to
make sure the radio button selected is an allowable option. The text displayed
within the control is set with the Text property, which can contain access key
shortcuts. An access key allows a user to "click" the control by pressing the ALT
key with the access key.
GroupBox Control
Windows Forms GroupBox controls are used to provide
an identifiable grouping for other controls. Typically, you
use group boxes to subdivide a form by function. For
example, you may have an order form that specifies
mailing options such as which overnight carrier to use.
Grouping all options in a group box gives the user a
logical visual cue, and at design time all the controls can
be moved easily — when you move the single GroupBox
control, all its contained controls move, too.
RadioButtons in a GroupBox
Sample Code
If RadioButton1.Checked Then
Label6.Text = Label5.Text
' Horizontal Forward
ElseIf RadioButton2.Checked Then
For i = Label5.Text.Length - 1 To 0 Step -1 ' Horizontal Reversed
Label6.Text = Label6.Text + Label5.Text.Substring(i, 1)
Next i
ElseIf RadioButton3.Checked Then
' Vertical Forward
For i = 0 To Label5.Text.Length - 1
Label6.Text = Label6.Text + Label5.Text.Substring(i, 1) + vbCrLf
Next i
ElseIf RadioButton4.Checked Then
For i = Label5.Text.Length - 1 To 0 Step -1 ' Vertical Reversed
Label6.Text = Label6.Text + Label5.Text.Substring(i, 1) + vbCrLf
Next i
Else
MessageBox.Show("No Radio Button Checked!", "Missing Radio Button",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
ComboBox Control
• ComboBox
– Combines TextBox features with drop-down
list
– Drop-down list
• Contains a list from which a value can be selected
• Scrollbar appears if necessary
ComboBoxes
ComboBoxes
ComboBox events and
Description / Delegate and Event Arguments
properties
Common Properties
DropDownStyle
Determines the type of combo box. Value Simple means that the
text portion is editable and the list portion is always visible. Value
DropDown (the default) means that the text portion is editable, but
the user must click an arrow button to see the list portion. Value
DropDownList means that the text portion is not editable and the
user must click the arrow button to see the list portion.
Items
The collection of items in the ComboBox control.
MaxDropDownItems
Specifies the maximum number of items (between 1 and 100) that the
drop-down list can display. If the number of items exceeds the
maximum number of items to display, a scrollbar appears.
SelectedIndex
Returns the index of the selected item. If there is no selected item, -1
is returned.
SelectedItem
Returns a reference to the selected item.
Sorted
Indicates whether items are sorted alphabetically. Setting this
property’s value to True sorts the items. Default is False.
Common Event
(Delegate EventHandler, event arguments EventArgs)
SelectedIndexChan Generated when the selected index changes (such as when a different
ged
item is selected). This is the default event when control is doubleclicked in designer.
ComboBoxes
ComboBoxes
Sample Code To Access Value
If no value is selected from a ComboBox the value
of ComboBox.Text = “”
Otherwise the selected value is in ComboBox.Text
Sample Code – To Insert
Dim i As Integer
Dim bFound As Boolean = False
iAdded = Label5.Text.Length / 2
For i = 0 To ComboBox1.Items.Count - 1
If ComboBox1.Items(i) = iAdded.ToString Then
bFound = True
Exit For
End If
Next
If Not bFound Then
ComboBox1.Items.Add(iAdded.ToString)
End If
'ComboBox1.Sorted = True
Sample Code – To Remove
For i = 0 To ComboBox1.Items.Count - 1
If ComboBox1.Items(i) = iAdded.ToString Then
ComboBox1.Items.RemoveAt(i)
Exit For
End If
Next i
iAdded = 0
Using F1 or Search for Help
• To Use Visual Studio.NET Help function,
you can either:
– Place the cursor on the control or command in
question and type an F1
or
– Bring up the Help Search Window
Help  Search
– Enter the desired topic
In Class Exercise
Write a Windows Form Version of the
Name Lister Program
More Windows Controls
The Use of Date and Time
•
•
•
•
DateTime Data Type
DateTimePicker and Timer Controls
Format and DateDiff Functions
Class Problem 2 / Clock Program
DateTime Data Type
• DateTime Structure
• Represents an instant in time, typically
expressed as a date and time of day.
DateTime Member Functions
• Now
Dim today As DateTime = Now
• Year, Month, Day, Hour, Minute, Second
Dim Year As Integer = today.Year
Dim Minute As Integer = DateTime.Now.Minute
• DateTime.Now.ToLongDateString
Label5.Text = DateTime.Now.ToLongDateString
• DateTime.Now.ToLongTimeString
Label5.Text = DateTime.Now.ToLongTimeString
DateTimePicker Control
• Tool for Selecting a Date
• Returns Date Selected in DateTime format
DateTimePicker Control
The Windows Forms DateTimePicker control
allows the user to select a single item from a list of
dates or times. It appears in two parts: a drop-down
list with a date or time represented in text, and a
grid that appears when you click on the downarrow next to the list. The grid looks like the
MonthCalendar control, which can be used for
selecting multiple dates.
DateTimePicker Sample Code
difHours = DateDiff("h", DateTimePicker1.Value,
DateTimePicker2.Value)
Timer Control
The Windows Forms Timer is a component
that raises an event at regular intervals. This
component is designed for a Windows Forms
environment.
Timer Control Sample Code
• Timer Properties
– Enabled  True or False
– Interval  The number of milliseconds between each timer tick.
The value is not less than one. To get the number of seconds in the
interval, divide this number by 1,000.
Private Sub Timer1_Tick(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Timer1.Tick
Label3.Text = DateTime.Now.ToLongTimeString
Label5.Text = DateTime.Now.ToLongDateString
End Sub
Format Function
Returns a string formatted according to
instructions contained in a format String
expression.
Note: The String.Format method also provides
similar functionality.
Sample Number Formatting Code
MyStr = Format(23) ' Returns "23" ' User-defined numeric formats.
MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00") ' Returns "334.90".
MyStr = Format(5, "0.00%") ' Returns "500.00%".
Label10.Text = Format(difDays, "###,##0.00")  difDays is a Double
Label9.Text = Format(difWeeks, "###,##0.00")  difWeeks is a Double
Sample Date Formating Code
Dim MyDateTime As Date = #1/27/2001 5:04:23 PM#
Dim MyStr As String' Returns current system time in the system-defined
long time format
MyStr = Format(Now(), "Long Time")' Returns current system date in the
system-defined long date format
MyStr = Format(Now(), "Long Date")' Also returns current system date in
the system-defined long date ' format, using the single letter code for the
format
MyStr = Format(Now(), "D")' Returns the value of MyDateTime in userdefined date/time formats
MyStr = Format(MyDateTime, "h:m:s") ' Returns "5:4:23"
MyStr = Format(MyDateTime, "hh:mm:ss tt") ' Returns "05:04:23 PM"
MyStr = Format(MyDateTime, "dddd, MMM d yyyy") ' Returns "Saturday,
' Jan 27 2001"
MyStr = Format(MyDateTime, "HH:mm:ss") ' Returns "17:04:23“
DateDiff Function
Returns a Long value specifying the
number of time intervals between two
Date values.
Sample Date Diff Code
Dim difHours As Long
difHours = DateDiff("h", DateTimePicker1.Value,
DateTimePicker2.Value)
Can also use:“h” result in hours
Enumeration value
Unit of time
difference
String
DateInterval.DayOfYear
y
Day
DateInterval.Day
d
Day
DateInterval.Hour
h
Hour
DateInterval.Minute
n
Minute
DateInterval.Month
m
Month
DateInterval.Quarter
q
Quarter
DateInterval.Second
s
Second
DateInterval.Weekday
w
Week
DateInterval.WeekOfYear
ww
Calendar week
DateInterval.Year
yyyy
Year
In Class Exercise
Clock Program
Homework Assignment