visual basic.net programming january 21, 2004. class agenda – january 21, 2004 homework open...
TRANSCRIPT
Class Agenda – January 21, 2004Homework
Open Questions?
Programming Paradigm's
Program Design Tools
Review Homework Assignment
Modular Programming
Visual Basic.NET Language Features
Class ExerciseWrite a Modular Name ListerIntroduction 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
Concatenation Operators
• & Operator
result = expression1 & expression2
• + Operator
expression1 + expression2
& Operatorresult = 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 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...
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
1. Enter First Name (if empty error, try again)
2. Enter Middle Name
3. Enter Last Name (if empty error, try again)
4. Concatinate Name Fields build full name
5. Check Length (if > 20 then shorten full name)
6. Request display type (horizontal or vertical, forward or backward) display accordingly
7. add loops (another display? another name? exit logic...)
Flow Charting
• Flowcharts– Graphical representation of an algorithm– Drawn using certain special-purpose symbols
• Rectangles
• Diamonds
• Ovals
• Small circles
add grade to total
add 1 to counter
total = total + grade
counter = counter + 1
Flowcharting Visual Basic’s sequence structure.
Grade >= 60true Console.WriteLine(“Passed”)
false
Flowcharting a single-selection If/Then structure.
Flowcharting a double-selection If/Then/Else structure
Grade >= 60true Console.WriteLine(“Passed”)false
Console.WriteLine(“Failed”)
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...)
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 Worker2 Worker3
Worker4 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 definitionSub procedure-name(parameter-list) declarations and statementsEnd 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 ArgumentsSub 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
• 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 ArgumentsPass-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.
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
• 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 KeywordsPrivate Property Protected Public RaiseEvent ReadOnly ReDim Region Rem RemoveHandler Resume Return Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until When While With WithEvents WriteOnly Xor #Const #If...Then...#Else - -= &
&= * *= / /= \ \= ^ ^= + += = 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 (2-byte) 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 TypeDecimal 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
• 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 expression1 AndAlso expression2
False False False
False True False True False False True True True
OrElse Logical Operator
expression1 expression2 expression1 OrElse expression2 False False False
False True True True False True True True True
Xor Logical Operator
expression1 expression2 expression1 Xor expression2
False False False
False True True True False True True True False
Precedence and associativity of the operators discussed so far.
Operators Associativity Type () left to right parentheses
^ left to right exponentiation + - left to right unary prefix * / left to right multiplicative \ left to right Integer division Mod left to right modulus + - left to right additive & left to right concatenation < <= > >= = <> left to right relational and equality Not left to right logical NOT And AndAlso left to right boolean logical AND Or OrElse left to right boolean logical inclusive OR Xor left to right 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
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 counter = 2 To 10 Step 2
For keyword
Initial value of control variable
Final value of control variable Increment of
control variable
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
• Binary operators– +, -, *, ^, &, / or \
variable = variable operator expression
variable operator= expression
• Example– Addition assignment operator, +=
value = value + 3
value += 3
Assignment Operators
Assignment operator
Sample expression
Explanation Assigns
Assume: c = 4, d = "He"
+= c += 7 c = c + 7 11 to c -= c -= 3 c = c - 3 1 to c *= c *= 4 c = c * 4 16 to c /= c /= 2 c = c / 2 2 to c \= c \= 3 c = c \ 3 1 to c ^= c ^= 2 c = c ^ 2 16 to c &= d &= "llo" d = d & "llo" "Hello" to d
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 ConstantsMember 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: Err.Raise(Number) = vbObjectError + 1000
Tab vbTab Chr(9) Tab 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 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 ButtonsMessageBoxButton constants Description
MessageBoxButton.OK 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- Ignore
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..
MessageBox IconsMessageBoxIcon Constants Icon Description
MessageBoxIcon.Exclamation 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.
MessageBoxIcon.Error Icon containing an in a red circle. Typically used to alert the user of errors or critical situations.
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).
Dialog Result - Specifies identifiers to indicate the return value of a dialog box.
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
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
• 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
• 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.
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
ComboBoxesComboBox events and properties
Description / Delegate and Event Arguments
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)
SelectedIndexChanged
Generated when the selected index changes (such as when a different item is selected). This is the default event when control is double-clicked in designer.
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
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
• NowDim today As DateTime = Now
• Year, Month, Day, Hour, Minute, SecondDim Year As Integer = today.YearDim Minute As Integer = DateTime.Now.Minute
• DateTime.Now.ToLongDateStringLabel5.Text = DateTime.Now.ToLongDateString
• DateTime.Now.ToLongTimeStringLabel5.Text = DateTime.Now.ToLongTimeString
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 down-arrow next to the list. The grid looks like the MonthCalendar control, which can be used for selecting multiple dates.
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 formatMyStr = Format(Now(), "Long Time")' Returns current system date in the system-defined long date formatMyStr = Format(Now(), "Long Date")' Also returns current system date in the system-defined long date ' format, using the single letter code for the formatMyStr = Format(Now(), "D")' Returns the value of MyDateTime in user-defined date/time formatsMyStr = 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