VB User Interface Objects - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

VB User Interface Objects

Description:

Problem: This will create a new instance of the form every time the button is clicked. ... Problem: Once the form is closed the variable is no longer exists. ... – PowerPoint PPT presentation

Number of Views:61
Avg rating:3.0/5.0
Slides: 45
Provided by: onlin
Category:
Tags: form | interface | objects | user

less

Transcript and Presenter's Notes

Title: VB User Interface Objects


1
VB User Interface Objects
2
VB 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.

3
Form
  • 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()

4
Multiple 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.
5
SharingVariables 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

6
Variables 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.

7
MsgBox
  • 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

8
MessageBox
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
9
InputBox
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
10
Text Box
  • Useful properties
  • Locked read only
  • Password Character
  • Multiline
  • ScrollBar
  • Text
  • Useful events
  • TextChanged
  • Validating

11
Input 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.

12
TextBox 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
13
Group 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.

14
Radio 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.

15
RadioButton 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
16
RadioButton 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
17
Check Box
  • Check boxes do not belong to a group even when
    they are grouped in a Group Box.
  • Checked property and checkedChangedevent

18
Check 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
19
Check 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
20
List 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

21
List 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
22
ListBox 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
23
CheckedListBox
  • 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

24
ToolTip
25
Status 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

26
ImageList
  • 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.

27
Arrays
  • 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.

28
Declaring 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)

29
Dynamic Array Example
Dim StudentAge() . ReDim StudentAge(TotalStudents
)
30
Control 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
31
Unstructured 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

32
Error 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
33
Structured 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
34
Collections
  • 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.

35
Using 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.

36
Iterating 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
37
Enumerations
  • 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

38
Enumerations
  • 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
39
More 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)

40
Declare 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.
41
Declare 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.
42
Close 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
43
Main 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.

44
Context 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.
Write a Comment
User Comments (0)
About PowerShow.com