File dialog boxes Function args and overloading - PowerPoint PPT Presentation

Loading...

PPT – File dialog boxes Function args and overloading PowerPoint presentation | free to download - id: 6f969e-OTAwN



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

File dialog boxes Function args and overloading

Description:

File dialog boxes Function args and overloading – PowerPoint PPT presentation

Number of Views:11
Avg rating:3.0/5.0
Slides: 42
Provided by: hig51
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: File dialog boxes Function args and overloading


1
File dialog boxes Function args and overloading
2
Examples in this show
  • List directory contents
  • Open a file for viewing
  • Read/Write to a file
  • Add file I/O to an old project
  • reading/writing array contents
  • Streamreader
  • Overloaded functions

3
Listing text files in a directory
4
File load
  • Private Sub Form1_Load(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load
  • txtfile.Text CurDir()
  • End Sub

5
the open button check for legal path
  • Dim NewPath As String
  • ' NewPath holds the path the user has
    entered.
  • NewPath txtfile.Text
  • ' Change the location to NewPath.
  • Dim errormessage As String
  • Try
  • ChDir(NewPath)
  • ' This checks to make sure the path
    is not blank.
  • Catch ex As Exception When NewPath ""
  • ErrorMessage "You must enter a
    path."
  • ' This catches errors caused by a
    path that is not valid.
  • Catch
  • ErrorMessage "You must enter a
    valid path. If trying" _
  • "to access a different drive,
    remember to include the drive" _
  • "letter."
  • Finally
  • ' Display the error message only if
    one exists.
  • If ErrorMessage ltgt "" Then
  • MsgBox(ErrorMessage)

6
Display txt contents of directory
  • Dim contentitem As String
  • lstData.Items.Clear()
  • ' Only look at the .txt files.
  • ContentItem Dir(".txt")
  • If ContentItem "" Then
  • errormessage "No text files found."
  • MsgBox(errormessage)
  • End If
  • ' Iterate through the directory contents.
  • Do Until ContentItem ""
  • ' Add it to the list.
  • lstData.Items.Add(contentitem)
  • ' Move to the next textfile.
  • ContentItem Dir()
  • Loop

7
Using filedialogs this is a dialog box
8
Open and save file dialog boxes are in your
toolbox and are added to the component tray
9
Button action
  • Open and save buttons display the file dialog,
    get the results of the dialog.
  • If the result is cancel the sub is exited via a
    return
  • If the filename doesnt end in .txt (not a
    guarantee of anything) the sub is exited. We do
    this by using the endswith() string function to
    check the end of the string.
  • I added a try catch in the hopes of eliminating
    file io exceptions which might shut down the
    application.

10
Button action open
  • The open button gets a filename, opens a
    filereader for a file with this name.
  • As long as there is more text in the file we read
    it and append it to our multiline textbox.

11
Button action Save
  • The save button gets a filename from the dialog
    (or a cancel), opens a filewriter for a file with
    this name.
  • As long as there is more text (ie. Line by line)
    in the multi-line textbox we read it and append
    it to our multi-line textbox. (Multi-line
    textbox is just a textbox with multi-line
    property set to true).
  • We do this by using indexof string function to
    find a crlf in the contents string and the
    substring function to cut this part off.

12
Open button
  • Private Sub btnopen_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnopen.Click
  • Dim objinput As StreamReader
  • Dim tmp, filename As String
  • Dim result As DialogResult
    windows.forms.objOpenFileDialog.ShowDialog
  • If result DialogResult.Cancel Then
  • Return
  • End If
  • filename objOpenFileDialog.FileName
  • If filename.EndsWith(".txt") False Then
  • Return
  • End If
  • Try
  • objinput New StreamReader(filename)
  • Dim contents As String
  • contents objinput.ReadLine
  • Do While contents ltgt ""
  • txtContents.AppendText(contents
    ControlChars.CrLf)
  • contents objinput.ReadLine
  • Loop

13
Save button
  • Private Sub btnSave_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnSave.Click
  • Dim objoutput As StreamWriter
  • Dim tmp As String
  • Dim result As DialogResult
    windows.forms.objSaveFileDialog.ShowDialog
  • If result DialogResult.Cancel Then
  • Return
  • End If
  • Dim filename As String
    objSaveFileDialog.FileName
  • If filename.EndsWith(".txt") False Then
  • Return
  • End If
  • Try
  • objoutput New StreamWriter(filename)
  • Dim contents As String
    txtContents.Text
  • objoutput.WriteLine(contents)
  • objoutput.Close()
  • Catch ex As Exception
  • End Try

14
Open button
15
Adding file output to a previous project
16
Recommended way to do file i/o
  • Use a streamwriter and streamreader objects (for
    writing or reading respectively).
  • Use a filedialog box for opening or saving a
    file.
  • This example should not be used as a basis for
    file io

17
The save button
  • Private Sub btnsave_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnsave.Click
  • ' FileOpen will create the file if it
    doesn't exist.
  • ' value 1 is the file handle
  • Dim errormessage, displaystring As String
  • Dim i, j As Integer
  • Try
  • FileOpen(1, "records.txt",
    OpenMode.Append) this should be redone with
    stream writer
  • For i 0 To classsize - 1
  • displaystring students(i)
  • For j 0 To 2
  • If exams(i, j) -99 Then
  • displaystring
    displaystring ControlChars.Tab "no grade"
  • Else
  • displaystring
    displaystring ControlChars.Tab exams(i, j)
  • End If
  • Next
  • WriteLine(1, displaystring)
  • Next
  • Catch ex As Exception

18
Open/View and Save
19
Open button provides dialog box
20
Open button code
  • Private Sub btnopen_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnopen.Click
  • Dim objinput As StreamReader
  • Dim tmp, filename As String
  • Dim result As DialogResult
    objOpenFileDialog.ShowDialog
  • If result DialogResult.Cancel Then
  • Return
  • End If
  • filename objOpenFileDialog.FileName
  • If filename.EndsWith(".txt") False Then
  • Return
  • End If
  • Try
  • objinput New StreamReader(filename)
  • Dim contents As String
  • contents objinput.ReadLine
  • Do While contents ltgt ""
  • txtContents.AppendText(contents
    ControlChars.CrLf)
  • contents objinput.ReadLine

21
Create a new file (type contents)
22
Dialog box for save button
23
Save button code
  • Private Sub btnSave_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnSave.Click
  • Dim objoutput As StreamWriter
  • Dim tmp As String
  • Dim result As DialogResult
    windows.forms.objSaveFileDialog.ShowDialog
  • If result DialogResult.Cancel Then
  • Return
  • End If
  • Dim filename As String
    objSaveFileDialog.FileName
  • If filename.EndsWith(".txt") False Then
  • Return
  • End If
  • Try
  • objoutput New StreamWriter(filename)
  • Dim contents As String
    txtContents.Text
  • objoutput.WriteLine(contents)
  • objoutput.Close()
  • Catch ex As Exception
  • End Try

24
Filling/saving array contents
25
Saved file contents
26
Save button open file and write to it
  • Private Sub btnsave_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnsave.Click
  • ' FileOpen will create the file if it
    doesn't exist.
  • ' value 1 is the file handle
  • Dim errormessage As String
  • Dim i As Integer
  • Dim outpt As StreamWriter
  • Try
  • outpt File.CreateText("values2.txt")
    'could use dialog box
  • For i 0 To array.Length - 1
  • outpt.WriteLine(array(i))
  • Next
  • Catch ex As Exception
  • errormessage ex.ToString()
  • MsgBox(errormessage)
  • Exit Sub
  • Finally
  • outpt.Close()

27
Open button open file and read from it
  • Private Sub btnopen_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnopen.Click
  • Dim input As streamreader
  • Dim errormessage As String
  • Dim i As Integer
  • lstData.Items.Clear()
  • Try
  • input File.OpenText("values.txt")
    'could use dialog box or textbox for name
  • For i 0 To array.Length - 1
  • array(i) CInt(input.ReadLine)
  • lstData.Items.Add(array(i))
  • Next
  • Catch ex As Exception
  • errormessage ex.ToString()
  • MsgBox(ErrorMessage)
  • Exit Sub
  • Finally
  • input.Close()
  • End Try
  • End Sub

28
notes
  • Could have used a file dialog, or got filename(s)
    from the textbox.
  • Global array declared
  • Need to import system.io for streamreader and
    streamwriter

29
Another streamreader example
30
About this example
  • Streamreader can be opened from a string
  • Need imports System.io at the top of the
    application.
  • I first checked if the file existed, then
    displayed all the file contents

31
Just the code for the open button
  • Private Sub btnopen_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnopen.Click
  • Dim fname, line As String
  • line " initialize the line to empty
  • Dim strmreader As System.IO.StreamReader
  • fname txtfile.Text get filenamea
    string
  • If File.Exists(fname) Then check if
    legal
  • strmreader System.IO.File.OpenText(f
    name) note code here
  • Do Until strmreader.Peek -1 and
    hereread to EOF
  • line strmreader.ReadLine
  • streamreader can read a line
  • lstdisplay.Items.Add(line)
  • Loop
  • Else
  • MessageBox.Show("illegal file name")
  • End If
  • End Sub

32
Reading individual characters file contents
  • 123 456 789
  • 12
  • 34
  • 56
  • 7

33
Display ASCII codes for chars
34
Using read (instead of readline)
  • Private Sub Button1_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles Button1.Click
  • Dim data As String
  • Lstdisplay.Items.Clear()
  • Dim sr As IO.StreamReader
    IO.File.OpenText("C\data.txt")
  • Do While sr.Peek ltgt -1
  • data sr.Read() 'read char by char
  • Lstdisplay.Items.Add(data)
  • Loop
  • sr.Close()
  • End Sub

35
The stream methods
36
Functions or subs may have optional arguments
  • You can specify that a procedure argument is
    optional and does not have to be supplied when
    the procedure is called. Optional arguments are
    indicated by the Optional keyword in the
    procedure definition. The following rules apply
  • Every optional argument in the procedure
    definition must specify a default value.
  • The default value for an optional argument must
    be a constant expression.
  • Every argument following an optional argument in
    the procedure definition must also be optional.
  • The following syntax shows a procedure
    declaration with an optional argument
  • Sub subname(ByVal arg1 As type1, Optional
    ByVal arg2 As type2 default)
  • Calling Procedures with Optional Arguments
  • When you call a procedure with an optional
    argument, you can choose whether to supply the
    argument. If you do not, the procedure uses the
    default value declared for that argument.
  • When you omit one or more optional arguments in
    the argument list, you use successive commas to
    mark their positions. The following example call
    supplies the first and fourth arguments but not
    the second or third
  • Call subname(arg1, , , arg4) ' Leaves out
    arg2 and arg3.

37
compute degrees F or C based on which is passed
  • Private Sub calc(Optional ByVal F As String
    Nothing, Optional ByVal C As String Nothing)
  • Dim convert As Double
  • Try
  • If F Is Nothing Then convert
    celsius temp to F
  • Dim celsius As Double CDbl(C)
  • convert 9 / 5 celsius 32
  • txtf.Text convert.ToString("n2")
  • Else must use F since C must be
    nothing
  • Dim fahr As Double CDbl(F)
  • convert 5 / 9 (fahr - 32)
  • txtc.Text convert.ToString("n2")
  • End If
  • Catch ex As FormatException
  • MessageBox.Show("at least on field must be a
    double")
  • End Try
  • End Sub
  • Private Sub btnconvert_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btnconvert.Click
  • If txtf.Text "" Then

38
Running optional args example
39
Overloaded functions
  • A function signature consists of the name, and
    parameters.
  • If function signatures differ (even though the
    names are the same), then VB, C, VC, java,
    etc, can distinguish which function you are
    trying to use.
  • So we could also code two versions of a given
    function.

40
Function overloading add ints, doubles and
strings

41
Function overload
  • Private Sub btndostuff_Click(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles btndostuff.Click
  • Dim s, t As String
  • s txtone.Text
  • t txttwo.Text
  • txtint.Text ADD(CInt(s), CInt(t))
  • txtdouble.Text ADD(CDbl(s), CDbl(t))
  • txtstring.Text ADD(s, t)
  • End Sub
  • Function ADD(ByVal s As String, ByVal t As
    String) As String
  • ADD s t
  • End Function
  • Function ADD(ByVal s As Integer, ByVal t As
    Integer) As String
  • ADD (s t).ToString
  • End Function
  • Function ADD(ByVal s As Double, ByVal t As
    Double) As String
  • ADD (s t).ToString("n3")
  • End Function
About PowerShow.com