Visual Basic 3 - PowerPoint PPT Presentation

About This Presentation
Title:

Visual Basic 3

Description:

Flags of the world (more picture boxes, images) Another picturebox/radiobutton example ... Illustrating OOP: Flags of the world. About this app ... – PowerPoint PPT presentation

Number of Views:159
Avg rating:3.0/5.0
Slides: 66
Provided by: higg2
Category:
Tags: basic | flags | of | the | visual | world

less

Transcript and Presenter's Notes

Title: Visual Basic 3


1
Visual Basic 3
  • Some new components
  • Some new capabilities
  • OOD/OOP

2
Index of projects covered in this ppt
  • Date time display
  • Format currency
  • Form with picture box, group boxes, radiobuttons
  • Flags of the world (more picture boxes, images)
  • Another picturebox/radiobutton example
  • Images from file example with combobox
  • Changing fonts using current property settings or
    font literal values

3
Some points about class programming practices
  • Try to use conventional names in your projects.
    It will make them easier to edit and code
  • Some of you need more practice with arithmetic
    and with using data supplied in a textbox. You
    may need to take time outside of class to work on
    optional exercises or class projects.
  • Note If you dont show me your labs or projects,
    I do not mark them as complete. It is your
    responsibility to make sure I see your completed
    work. If I havent seen your project during the
    class period, show me after class I have office
    hour then. If you are not sure if I marked you
    come see me (F239) during office hour or email me
    which lab or project you want to know about.

4
Some points about class programming practices
  • Your text, section 3.3 goes over how to perform
    calculations with numbers.
  • Read this section of the text and do the
    exercises.
  • Complete the operator practice form from the last
    slideshow.

5
An aside Foreground and background colors
  • Users do best with grayscale coloring. But you
    can modify foreground and background color
    settings. In the forms properties select
    backcolor.

6
Select custom, web or system
7
Select a color from the palette
8
Declaring/initializing variables
  • Variables are declared using dim in VB
  • Dim name as String
  • Dim value as Integer
  • Dim val,num,x,y,z as Double
  • You can initialize variable values when you
    declare them, as in
  • Dim value as integer 100
  • Dim name as String Bob

9
You can declare constants
  • Const pi as double3.1412
  • Const ourbusiness as StringVB Inc
  • Const basehours as single40.0
  • Constants may not be altered by assigning them a
    new value later in your program. Typically,
    they would be declared at the class level (not
    discussed yet), just below the line at the top of
    your code view
  • Public class
  • put Global vars and consts here

10
A date literal
  • Date literals must appear within symbols.
  • They may contain date, time or both
  • Example formats
  • 12/10/2006
  • 313 PM
  • 211502 military
  • 12/10/2006 313 PM

11
Conversions for date
  • You can convert date format values or strings to
    date type as in
  • Dim startdate, thedate as date
  • Dim stringval as string 12/3/2005
  • Startdate 12/3/2005 10000 AM
  • thedateSystem.convert.todatetime(stringval)

12
Formatting dates as Strings for display
  • Dateformat.generaldate() will return dd/mm/yyyy
    if the date is just a date, otherwise see below
    for longtime
  • Dateformat.longdate gives day of week, month and
    day, no time returned as in Saturday, August 10,
    2005
  • Dateformat.shortdate formats as in general date
    above, no time is reported.
  • Dateformat.longtime does not report date part,
    but gives time in long format as in 032218 PM
  • Dateformat.shorttime returns military time in
    format HHMM
  • Access functions as
  • lblDateInfo.textFormatDateTime(someDate,DateForma
    t.shorttime)

13
Form to display current date/time on load
14
Date literals
  • Now returns the current day and time
  • Today returns the current day (no time)
  • TimeOfDay returns the current time, no date.

15
Onload code for previous form
  • Private Sub frmDayTime_Load(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load
  • Dim thedate As Date
  • thedate Today
  • lbldate.Text FormatDateTime(thedate,
    DateFormat.LongDate)
  • lbltime.Text FormatDateTime(thedate,
    DateFormat.LongTime)
  • End Sub

16
Percent formatting
  • You can format reals (single, double, decimal or
    literal values) as strings with percent format
    using the formatpercent() function
  • FormatPercent(.789) will return 78.9
  • FormatPercent(.48129) will return 48.13
  • FormatPercent(8.2) will return 820.00
  • FormatPercent(.3876,1) will return 38.7
  • Note the following it multiplies parameter by
    100 and then does a toString(). The default
    number of percentage places is 2.

17
Currency formatting
  • Real values can be formatted as currency using
    toString(C) or FormatCurrency

18
Button click code
  • Private Sub btndisplay_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btndisplay.Click
  • Dim value As Single Single.Parse(txtvalu
    e.Text)
  • lbldisplay1.Text lbldisplay1.Text ""
    value.ToString("C")
  • lbldisplay2.Text lbldisplay2.Text ""
    FormatCurrency(value.ToString())
  • End Sub

19
Lets build a new form
20
After clicking the image, typing new text and
selecting a radiobutton
21
New components are groupbox, radiobutton and
picturebox
  • Youll find these new components are pretty easy
    to use. From the toolbox
  • Select a groupbox and drop it on your form.
  • Now drop 3 radiobuttons into the groupbox.
  • Drop a picturebox on your form.
  • And another, right on top of the first.
  • Add two labels and a textbox.

22
Set properties
  • Our text uses radXXX to name radioButtons. I
    noticed another text used names like
    greenRadioButton and inputTextBox. I will allow
    you to follow that convention if you wish.
  • I also noticed our text leaves default names for
    controls which are not accessed in subroutines,
    though youll have to be careful. I will also
    allow you to follow this example.
  • You should not generally need to reference
    groupboxes, or even labels, unless the text on
    them is used for result-display purposes.
  • I left my groupbox and pictureboxes with their
    default names.
  • Name your labels and textbox and set their text
    properties.

23
properties
  • I set the font of my lblMessage to be symbol
    (greek).
  • For each picturebox, I selected the image
    property and then clicked the () to open a
    Select Resource Dialog Box and browsed my system
    to find some images.

24
Setting the image
25
What functionality do we want?
  • Radiobuttons should change the color of the
    displayed text (in lblMessage).
  • Since these are in a groupbox, VB will handle the
    exclusionary aspect of the functionality.
  • When one image is clicked, I want it to go away
    and the other to be displayed.

26
Tab ordering when using group boxes
  • Group boxes get tab ordering relative to other
    controls on your form, then controls inside a
    group box are ordered relative to each other.

27
Subroutines needed
  • Click on a radiobutton and provide code like
    messageLabel.ForeColor Color.Green
  • to the stubbed subroutine. Heres a complete
    example
  • Private Sub greenRadioButton_CheckedChanged(ByVal
    sender As System.Object, ByVal e As
    System.EventArgs) Handles greenRadioButton.Checked
    Changed
  • messageLabel.ForeColor Color.Green
  • End Sub

28
Coming attractions a problem with the code in
the previous slide
  • Green radio button checked changed event is
    fired when green radiobutton is selected or
    unselected. The code in the previous slide works
    because, when blue (for example) is selected,
    first green rb checked changed event is fired,
    then blue rb checked changed is fired, so the
    users current choice is updated properly. Well
    learn in a couple of weeks how to improve the
    event handler code to check whether the rb is
    CURRENTLY checked with a control structure called
    if then
  • If greenradiobutton.checked then
  • messageLabel.ForeColor Color.Green
  • End if

29
Subroutines needed
  • Click a picturebox. Add code like this to one
    stubbed method (and the opposite code to the
    other)
  • PictureBox2.Visible False
  • PictureBox1.Visible True
  • Heres one of the two complete subroutines
  • Private Sub PictureBox2_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles PictureBox2.Click
  • PictureBox2.Visible False
  • PictureBox1.Visible True
  • End Sub

30
OOP Classes and variable scope
  • Classes consist of fields, constructors and
    methods.
  • In VB, methods are called subs.
  • Fields are variables declared at the top of the
    class, visible to all the subs and functions in
    the class. Such variables should not be redefined
    in a sub they are already available.
  • We have already been using class fields, like
    txtinput.text and methods, like txtinput.clear()
    or me.close() in our examples.

31
variable scope
  • Parameters to functions and subs have local
    scope. They live only within the sub or function
    and are not available elsewhere.
  • VB defines your controls for you (in hidden
    code). They are fields of the class and have
    global scope.
  • Variables dimensioned inside subs and functions
    also have local scope and cant be referenced
    outside the sub or function containing the
    definition.

32
variable scope
  • A variable which needs to be accessed in many
    subs will need to be passed to each, or declared
    as a class field.

33
Illustrating OOP Flags of the world
34
About this app
  • The Flags project contains checkboxes,
    radiobuttons, one picturebox and groupboxes.
  • Only checkboxes are new for us.
  • But updating the display involves putting a new
    image on the picture box, and changing the text
    in the country label.

35
About this app
  • Well need to be able to get images from files.
  • Well need to keep track of the current country.
  • Since multiple subs need to update the display we
    will create our own sub called updateDisplay.
  • What parameters does updateDisplay need?

36
What parameters does updateDisplay need?
  • There are as usual- many ways of doing it.
  • The simplest might be to have a (class) field
    value (String) which holds the current country
    name. Well call it country. The code
  • Dim country as String goes near the top of our
    code, but after the start of the class definition

37
Controls and their properties
  • Not following VB convention, I named radiobuttons
    USARadioButton (etc)
  • In their properties, I set initial visibility of
    my two labels to false.
  • I initialized country string and flaglabel text
    to USA.
  • Flaglabel text is initialized in properties.
  • Country is initialized in the class constructor
    after the call to super.

38
the constructor
  • Public Sub New()
  • MyBase.New()
  • country "usa must go here since it
    is displayed
  • 'This call is required by the Windows
    Form Designer.
  • InitializeComponent()
  • 'Add any initialization after
    InitializeComponent() call
  • End Sub

39
More about this app
  • Well need to get images from files. To do this
    we need to import some capability we havent used
    yet System.io. The code
  • Import system.io goes right at the top of our
    code.
  • Each radiobutton event handler just changes the
    name of the current country and calls the sub
    updateDisplay() passing it the country name.
  • The checkbox event handlers simply set labels to
    visible or invisible based on whether they
    themselves are checked.

40
Code for one of the radiobuttons
  • Private Sub SwedenRadioButton_CheckedChanged(ByVal
    sender As System.Object, ByVal e As
    System.EventArgs) Handles SwedenRadioButton.Checke
    dChanged
  • updateDisplay("Sweden") that is all we
    need to do
  • End Sub

41
Code for updateDisplay
  • Private Sub updateDisplay(ByVal countryname As
    String)
  • country countryname update field value
  • flagLabel.Text country
  • need to get another imageglue on country name
  • MyPictureBox.Image Image.FromFile(Direct
    ory.GetCurrentDirectory country ".gif")
  • End Sub

42
Code for one of the checkbox clicked event
handlers
  • Private Sub countryCheckBox_CheckedChanged(ByVal
    sender As System.Object, ByVal e As
    System.EventArgs) Handles countryCheckBox.CheckedC
    hanged
  • set flaglabel visibility to true or false
    depending on the checkbox setting
  • flagLabel.Visible countryCheckBox.Checke
    d
  • End Sub

43
Image files
  • Youll need to copy whatever flag images you want
    into the current project directory.
  • Youll need to give them names like binUSA.gif
  • VB attaches the bin to the front of the file
    name when you get the directory in the debugger,
    but not when it is run as an exe file.
  • To deploy the app as an executable youll have to
    fix the path name for the flag gif files and
    possibly copy the gif files to wherever the
    application is supposed to run from.

44
Exercise Digit extraction
  • Allow the user to enter a five-digit number.
  • Display the digits, each in its own read-only
    textbox.
  • Provide Enter and Clear buttons.

45
GUI
46
Notes
  • Make the output textboxes read only.
  • Set the maximum length property of the input
    textbox to 5.
  • Use layout managers to get the alignments and
    sizes right.
  • Use the mod operation to get the ones place
    value. Then use the \ operation to go on to the
    next digit.

47
Notes
  • You could provide this functionality many ways.
  • Later in the semester well learn to do it by
    chopping the input string up into pieces 1
    character long each.

48
Another exercise Message formatter
49
Radio buttons control color
  • Private Sub rbRed_CheckedChanged(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles rbRed.CheckedChanged
  • Me.lblMessage.ForeColor Color.Red
  • End Sub

50
Checkbox determines if message should be displayed
  • Private Sub cbMessage_CheckedChanged(ByVal
    sender As System.Object, ByVal e As
    System.EventArgs) Handles cbMessage.CheckedChanged
  • Me.lblMessage.Visible cbMessage.Checked
  • End Sub

51
Button click may display message
  • Private Sub btnClear_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnClear.Click
  • With Me
  • With .txtName
  • .Clear()
  • .Focus()
  • End With
  • .txtMessage.Clear()
  • .lblMessage.Text ""
  • End With
  • End Sub

52
Click on picturebox to toggle picure box display
53
Pictureboxes event code
  • Private Sub pbBig_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles pbBig.Click
  • pbBig.Visible False
  • pbLittle.Visible True
  • End Sub
  • Private Sub pbLittle_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles pbLittle.Click
  • pbLittle.Visible False
  • pbBig.Visible True
  • End Sub

54
Getting images
55
More on images and fonts
56
Combobox image.fromFile
57
Combo box
  • Select the collection property to populate the
    combo box
  • I used
  • Picturebox.imageimage.fromfile(C\penguin.gif)
  • My combobox selected index changed sub code is
    below
  • If cbbchoose.Text "dog" Then
  • pb.Image Image.FromFile("c\dog.gif"
    )
  • ElseIf cbbchoose.Text "bear" Then
  • pb.Image Image.FromFile("c\bear.gif
    ")
  • Else
  • pb.Image Image.FromFile("c\penguin.
    gif")
  • 'pb.Refresh()
  • End If
  • Note I didnt take time to figure out how to get
    it to look in the application directory

58
Changing fonts via button press
59
I didnt figure out how to get a font literal in
this application
60
code
  • Private Sub btnfont3_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnfont3.Click
  • lbldisplay.Font btnfont3.Font()
  • End Sub
  • Private Sub btnfont1_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnfont1.Click
  • lbldisplay.Font btnfont1.Font()
  • End Sub
  • Private Sub btnfont2_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnfont2.Click
  • lbldisplay.Font btnfont2.Font()
  • End Sub

61
Literal font names
62
Press button to change font
63
code
  • Private Sub btn3_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btn3.Click
  • Dim f As New System.Drawing.Font("Arial",
    10)
  • ' Assign the font to the control
  • lbl1.Font f
  • ' To set additional properties, you must
    create a new Font object.
  • lbl1.Font f
  • 'lbl1.Font New System.Drawing.Font(lbl1.
    Font, FontStyle.Bold Or FontStyle.Italic)
  • End Sub
  • Private Sub Btn2_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles Btn2.Click
  • Dim f As New System.Drawing.Font("Symbol",
    12)
  • lbl1.Font f
  • ' or use...
  • 'lbl1.Font New System.Drawing.Font(f,
    FontStyle.Bold)
  • End Sub
  • Private Sub btn1_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btn1.Click
  • Dim f As New System.Drawing.Font("SansSeri
    f", 12)
  • lbl1.Font f
  • lbl1.Font New System.Drawing.Font(lbl1.F
    ont, FontStyle.Underline)
  • End Sub

64
Image.fromfile(P\...) does work in F306 lab a
screenshot
65
Code for previous slide
  • Private Sub Form1_Load(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load
  • PictureBox1.Image Image.FromFile("p\afr
    ica1.jpg")
  • End Sub
Write a Comment
User Comments (0)
About PowerShow.com