Title: VB User Interface Objects
1VB User Interface Objects
2VB User Interface Objects
- Form
- Menu
- DropDown menu, ToolTip
- InputBox, MsgBox, MessageBox
- Standard Controls
- Text Box, List Box, Option Button, Check Box,
Command Button, GroupBox, etc.
3Form
- Methods
- Me.show(), Me.Hide, Me.Close
- Events
- Load, Activated, Closing, Closed
- Modeless form Other forms can receive input
focus while this form remains active. - Modal form No other form can receive focus while
this form remains active. - Formname.ShowDialog()
4Multiple Forms
Two forms Form1, Form2 To Open Form2 from
Form1 Dim f2 As New Form2()
f2.Show() Open Form2 as a Modal
form f2.ShowDialog() Note Form is defined as
a class. Must create an instance of the form
class by using the keyword New to access the form.
5SharingVariables Among Forms
- Define these variables with class-level scope
using the Public keyword. - Must use formName to qualify variables.
-
- Dim f2 As New Form2()
- TextBox1.Text f2.g2 g2 is declared in
form2
6Variables Shared by Multiple Forms
- Define these variables with project-level scope
in a module using the Public keyword - Module Module1
- Public testVar As Integer
- End Module
- Note Use Project/Add Windows form to add a
module.
7MsgBox
- MsgBox(prompt, other arguments)
- MsgBox can return a value representing the users
choice of buttons displayed by the box. The
return value has MsgBoxResult data type - Dim RETurnVal As MsgBoxResult
- RETuranVal MsgBox("customer click cancel",
MsgBoxStyle.AbortRetryIgnore) - If RETurnVal MsgBoxResult.Abort Then
- MsgBox("YOU CLICK ABORT")
- End If
8MessageBox
MessageBox.Show(message) MessageBox.Show(message,
Caption) MessageBox.Show(message, Caption,
Buttons) Note 1. In each format, arguments are
positional and required. 2. This object returns a
DialogResult data type. To test the return
value Dim ReturnVal as DialogResult ReturnValM
essageBox(hello, ..) If ReturnValDialogResult
.OK
9InputBox
InputBox(Prompt ,Title , Default , Xpos ,
Ypos) Xpos is the distance from the left edge of
the screen, and Ypos is the distance from the top
of the screen. Both are measured in twips
(1/1440th of an inch). Note The arguments are
positional and optional. Enter a comma to skip
an argument. cityName InputBox("Please enter
city name, , SF) If cityName vbNullString
Then MessageBox.Show ("customer click
cancel") Else Text1.Text cityName End If
10Text Box
- Useful properties
- Locked read only
- Password Character
- Multiline
- ScrollBar
- Text
- Useful events
- TextChanged
- Validating
11Input Validation
- Numbers are checked to ensure they are
- Within a range of possible values
- Reasonableness
- Not causing problems such as division by 0.
- Containing only digits
- IsNumeric
- Textbox
- Set CauseValidation property to true.
- Use the Validating event
- Triggered just before the focus shifts to other
control.
12TextBox Validating Event
Private Sub TextBox1_Validating(ByVal sender As
Object, ByVal e As System.ComponentModel.CancelEve
ntArgs) Handles TextBox1.Validating If
Not IsNumeric(TextBox1.Text) Then
e.Cancel True MsgBox("enter digits
only") Else MsgBox("good")
End If End Sub
13Group Box and Panel
- Controls in a Group Box should move with the
boxs. - A panel control can display scrollbars by setting
the AutoScroll property to true.
14Radio Button
- Radio buttons must be grouped together inside a
container such as a GroupBox or a form. - When the user selects an option all other options
in the same group are deselected. - Checked property value True/False.
- Default button Set the Checked property to true
at the design time.
15RadioButton Example 1
Private Sub RadioButton1_CheckedChanged(ByVal
sender As System.Object, ByVal e As
System.EventArgs) Handles RadioButton1.CheckedChan
ged If RadioButton1.Checked True Then
MsgBox("Check RadioButton1")
Else MsgBox("uncheck RadioButton1")
End If End Sub
16RadioButton Example 2
If radioButton1.Checkedtrue then textbox1.text
You select radio button 1 ElseIf
radioButton2.Checkedtrue then textbox1.textYou
select radio button 2 Else textbox1.textYou
select radio button 3 End If
17Check Box
- Check boxes do not belong to a group even when
they are grouped in a Group Box. - Checked property and checkedChangedevent
18Check Box Example 1
Private Sub CheckBox1_CheckedChanged(ByVal sender
As System.Object, ByVal e As System.EventArgs)
Handles CheckBox1.CheckedChanged If
CheckBox1.Checked True Then
MsgBox(check chk1") Else
MsgBox("uncheck chk1") End If End Sub
19Check Box Example 2
Dim msg as String MsgYou choose If
checkBox1.checkedtrue then msgmsg check box
1 End If If checkBox2.checkedtrue then msgmsg
check box 2 End If If checkBox3.checkedtrue
then msgmsg check box 3 End If
20List Box
- Useful properties
- Items The items in the listBox. It is a
collection strcture. Items can be entered at the
design time or entered in code. - SelectionMode one or multi selection
- SelectedItem(s)
- Methods
- Add
- Clear
- Event SelectedIndexChange
21List Box Example
Private Sub Form1_Load(ByVal sender As Object,
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Clear() TextBox2.Clear()
ListBox1.Items.Clear()
ListBox1.Items.Add("Apple")
ListBox1.Items.Add("Orange")
ListBox1.Items.Add("Banana")
ListBox1.Items.Add("Strawberry")
TextBox2.Text ListBox1.Items.Count.ToString
End Sub Private Sub ListBox1_SelectedIndexCha
nged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ListBox1.SelectedIndexCh
anged TextBox1.Text ListBox1.SelectedIte
m End Sub
22ListBox Multiple Selections
Note The SelectionMode property must set to
multi selection. extBox2.Text
ListBox1.SelectedItems.Count.ToString Dim allSel
As String Dim i As Integer For i 0 To
ListBox1.SelectedItems.Count - 1 allSel
allSel ListBox1.SelectedItems.Item(i) Next
I Or use the For Each loop Dim item As
String For Each item In ListBox1.SelectedItems
allSel allSel item Next TextBox3.Text
allSel
23CheckedListBox
- ItemCheck event
- Private Sub CheckedListBox1_ItemCheck(ByVal
sender As Object, ByVal e As System.Windows.Forms.
ItemCheckEventArgs) Handles CheckedListBox1.ItemCh
eck - TextBox2.Text CheckedListBox1.SelectedIt
em - End Sub
24ToolTip
25Status Bar Timer
- Status Bar
- Panels
- Set ShowPanel property to true.
- StatusBar1.ShowPanels True
- StatusBarPanel1.Text System.DateTime.Now.ToStrin
g - Timer
- Private Sub Timer1_Tick(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Timer1.Tick StatusBarPanel1.Text
System.DateTime.Now.ToString - End Sub
26ImageList
- Manage a group of images. It is a repository of
images that your program can use for various
purposes. - Use the Images property to create list.
- Controls with the ImageList and ImageIndex
proerties , such as Button and Label, can use the
images in the list.
27Arrays
- Declaring arrays
- Dim arrayName(upperBound) As dataType
- Ex. Dim myArray(5) as Integer
- This array has 6 elements starting from 0.
- Dynamic arrays
- Ability to change the size of an array at run
time. - Use dynamic arrays when the size is unknown at
design time, or it varies from one time to
another.
28Declaring Dynamic Arrays
- Declare the array without specifying upper bounds
in the Dim statement. - Later, when the program needs a certain number of
elements in the array, use the ReDim statement to
assign the array size. - Each time a ReDim is executed, the values
currently stored in the array are lost. To keep
those data, use the Preserve keyword. - Ex. ReDim Preserve arrayName(NewUpperbound)
29Dynamic Array Example
Dim StudentAge() . ReDim StudentAge(TotalStudents
)
30Control Arrays
Dim ctrlArray(1) As Button Private Sub
Form1_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
ctrlArray(0) Button1 ctrlArray(1) Button2
TextBox1.Text ctrlArray(0).Text End
Sub
31Unstructured Error Handling
- On Error GoTo errorhandler (a label)
- Built-in Err object properties
- Number Error number
- Source Name of VB ile in which error occurred
- Description error message
- Continue the program execution
- Resume returns execution to the statement that
caused the error. - Resume Next
- Resume label Jumps to the line containing the
label. - Exit Sub
- Debug Debug.Print varName
32Error Handling Example
Private Sub cmdDivide_Click() On Error GoTo
DivideErrorHandler lalAnswer.CaptionCStr(CDbl(Tex
t1.text)/CDbl(Text2.Text)) Exit
Sub DivideErrorHandler MsgBox(CStr(Err.Number)
Err.Description) Exit Sub End Sub
33Structured Error Handling
Try result Val(TextBox1.Text) /
Val(TextBox2.Text) TextBox3.Text
result.ToString Catch except As
InvalidCastException
MessageBox.Show(except.Message) Catch
except As DivideByZeroException
MessageBox.Show(except.Message) Catch
except As Exception 'Handle
everything else MessageBox.Show(except
.Message) Finally
MessageBox.Show("I get exdecuted, no matter
what") End Try
34Collections
- Collections are used to store lists of objects.
- More flexible than array
- No need to declare the number of objects in a
collection, no need to ReDim. - Objects can be added, deleted at any position.
- Object can be retrieved from a collection by a
key. - A collections name usually end with a s.
35Using Collections
- Define a collection
- Ex. Dim Pets as New Collection
- Methods
- ADD Add object to a collection
- Pets.Add(dog)
- Add an object with a key
- Pets.Add(Dog, D)
- Item Retrieve an object from a collection with a
position index (base 1) or with a key. - petName Pets.Item(1)
- petName Pets.Item(D)
- Count Return the number of objects in a
collection. - Remove Delete an object with a position index or
key.
36Iterating Through a Collection
Dim Pets as New Collection Dim Indx as Long For
Indx 1 to Pets.Count operations Next
Indx For Each pet in Pets operations Next pet
37Enumerations
- Provide a way to associate meaningful names with
a sequence of constant values. - Define an enumeration using an Enum statement.
- Private Enum seasonOfYear
- Spring 1
- Summer 2
- Fall 3
- Winter 4
- End Enum
- Dim Sales(Spring to Winter) as Double
38Enumerations
- Provide a way to associate meaningful names with
a sequence of constant values.
Enum enumTest spring 1 summer
fall winter End Enum Dim etest
As enumTest Private Sub Form1_Load(ByVal sender
As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load etest enumTest.summer
TextBox1.Text Val(etest).ToString
39More about Form
- A form must be instantiated in a variable
- Dim F1 as New Form1()
- Useful methods
- Show Loads and display a modeless form.
- Activate set focus to the form.
- BringToFront
- Hide
- ShowDialog
- Close Unloads the form (the forms instance
variable no longer exists)
40Declare Forms Instance Variable in An Open Form
Event Procedure
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click Dim f2 As New
Form2() f2.Show() End Sub Problem
This will create a new instance of the form every
time the button is clicked.
41Declare Forms Instance Variable in a Module as
Public Variable
Module Module1 Public f1 As New Form1()
Public f2 As New Form2() End Module It can be
accessed in a procedure Private Sub
Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles
Button1.Click f2.Show() End
Sub Problem Once the form is closed the
variable is no longer exists. Attempt to access
it again will trigger error.
42Close Form Or Hide Form
Use a forms Closing event to change Close to
Hide Private Sub Form2_Closing(ByVal sender As
Object, ByVal e As System.ComponentModel.CancelEve
ntArgs) Handles MyBase.Closing e.Cancel()
True Me.Hide() End Sub
43Main Menu Control
- Add MainMenu control and follow the TypeHere
instruction. - Each submenu and each item on a submenu is
represented by a MenuItem control. - Use an to specify an access key in the caption.
Ex. File, Shos - Write an event procedure for each menu item.
44Context Menu
- A context menu is a menu that displays when an
object on the screen is right-clicked. - Add the ContextMenu control (it is placed in a
tray under the form). Right-click the control
and choose Edit to create the menu. - Use the objects ContextMenu property to bind the
object to the context menu.