Beginning Visual Basic (Visual Studio 2008) - Project 10

Project 10

Close your last project and creating a new one

If you still have the Project9 project open, select the Close Project item on the file menu to close it.

With no open projects, click on the Project... option next to Create: on the Start Page, or pick New Project item on the File drop-down menu. 

The Add New Project dialog appears.  With the Windows Application template selected, type Project10-11 for the name and click the OK button—We will be using this project for project 11 also.  Now click the Save All button on the toolbar to save the project.  Be sure to uncheck the Create directory for solution option on the Save Project dialog box.  Do not change the default Location path and click the Save button. 

This creates a new folder inside the My Documents\Visual Studio 2008\Projects\  folder named Project10-11:

        My Documents\Visual Studio 2008\Projects\Project10-11

Rename the Form file and the Form

With the form file (Form1.vb) selected in the Solution Explorer window, the Properties window directly below it displays it's File properties.  Click on the File Name property and type frmProj10.vb (don't forget to include the .vb extension).  To display the properties of the form in the Properties window, click once on the blank Form, which should be displayed on the left side of the screen in the Design window.  Make sure the Name property—which is in parentheses (Name) at the top of the property list so that it's easy to find—is frmProj10.  Then scroll the properties windows down and change the Text property to Project 10.

Before going on, click on the Save All button on the toolbar to save your project.
 


For your tenth Visual Basic project, you will create a program with 2 Textboxes and a simple Menu. The first Textbox will allow the user to type text and then save it to a file by choosing Save from the Menu. The second Textbox will allow the user to view text files (.txt) that the user opens with the Open menu item.

Creating the Menu

Menu Table
Level 1
Text
Level 2
Text
Name
&File   mnuFile
  &New mnuNew
  &Open mnuOpen
  &Save mnuSave
  (Insert Separator)  
  E&xit mnuExit

Oh look! A File menu that actually has something to do with files!  Use the Menu Table above as a guide and create the Menu. Hint: As before, begin by adding a MenuStrip control to the Component Tray, then set the MainMenuStrip property of the form to MenuStrip1.  Use the Menu Table above to guide you, when adding items to the menu.

Adding Textboxes and Labels to the Form

Use the illustration below and place two Labels and two Textboxes as shown:

Set their properties like this:

Left Label Right Label
Property Value Property Value
Text Enter Text: Text View Text:
Font Bold Font Bold
Left Textbox Right Textbox
Property Value Property Value
Name txtEnter Name txtView
Multiline True Multiline True
Scrollbars Vertical Scrollbars Vertical
BorderStyle Fixed3D BorderStyle FixedSingle
Text blank Text blank

 

 

 

 

 




Adding
OpenFileDialog and SaveFileDialog controls to the Component Tray

Scroll down the Control Toolbox.  From the Dialogs section, add one OpenFileDialog control and one SaveFileDialog control to the Component Tray:

Now your Component Tray should look like this:

Using a SaveFileDialog control to help you save files

Why do the Open file and Save file dialogs that most applications use look very similar to each other (see the illustration below)?  The idea of a Common User Interface is an important driving force behind the development of windows applications.  In theory, if all applications work in a similar way, a user will be more productive and take less time learning how to use new applications.  To that end, the Save and Open file dialog boxes look and behave the same way between different applications.  In fact, the code that generates these dialog boxes exists inside a Dynamic Link Library (DLL) file that is part of the operating system.  So the Save file and Open file dialog boxes don't just look the same between different applications; they are the same!

When we use a SaveFileDialog control, we are actually displaying the same Save dialog that most other applications will display.  This is how the SaveFileDialog looks.  This should look familiar to you:

Here is the code that uses the SaveFileDialog control to create the above Save dialog box.  Note: The excessive commenting is for your information.  Be sure to read them all, but you don't need to type them all into your program. Type the following code into the mnuSave_Click event procedure:

'Dimension an iResult variable to capture the DialogResult
'    returned by the SaveFileDialog so we can determine if
'    the user pressed the Cancel or Save button to close it.
Dim iResult As DialogResult
'Assign the dialog’s Title property (this is displayed in the
'    caption bar of the Save dialog).
SaveFileDialog1.Title = "Specify a Name for the File"
'The Filter property lets you specify which file types will to
'    be listed in the Save dialog. The text to the left of the
|
'    (vertical bar) is the text displayed in the Save As Type
'    dropdown listbox (shown above). The last part:
*.txt is
'    the actual filter specification, which means only files with
'    a TXT extension will be displayed.
SaveFileDialog1.Filter = "Text Files (*.txt) | *.txt"
'The AddExtension property makes sure that the .txt extension
'    is automatically added to any file name the user specifies.
SaveFileDialog1.AddExtension = True
'By setting the OverwritePrompt property to true, a warning
'    dialog will appear if the user attempts to save over an
'    existing file.
SaveFileDialog1.OverwritePrompt = True
'The InitialDirectory property lets you specify the start up
'    directory that is displayed when the Save dialog first opens.
SaveFileDialog1.InitialDirectory = "C:\"
'Clear the FileName property of SaveFileDialog1 prior
'    to displaying it.
SaveFileDialog1.FileName = ""
'The ShowDialog method displays the Save dialog.  Any
'    code that follows this line of code will not be executed
'    until the Save dialog is closed.
iResult = SaveFileDialog1.ShowDialog()

The code above does not actually save a file.  All it does is use the SaveFileDialog to display the Save dialog where the user specifies the name of the file to be saved—or they can browse and select an existing file to overwrite it.  It is still up to us to write the code that will save the contents of the txtEnter textbox to the file that the user specifies.

Creating a IO.FileStream object to write to a file

We need to create a FileStream to do file input and output.  We can dynamically create a FileStream object by dimensioning an instance of it with it's object constructor, like this (do not type the following code yet):

    Dim FStream As New _
        IO.
FileStream(
<File Name>, IO.FileMode.Create)

Using the FileStream method of the IO (Input/Output) class to create the FileStream object requires two parameters:

  1. The File Name—the name of the file to be created or opened, which must include the full path and name of the file.
  2. The FileMode—which determines how the file is to be opened.  The FileMode options that are available include, Append, Create, CreateNew, Open, OpenOrCreate, and Truncate.

Once we have created a FileStream object—which gives us a connection to the file and determines how it is opened—we can create a StreamWriter object for the FileStream that makes writing to the file easy, like this:

    Dim SWriter As New IO.StreamWriter(FStream)

The FStream parameter is the FileStream object we had just created.  Once the StreamWriter object is created we can write to the file with the Write method of the  StreamWriter, like this:

    SWriter.Write(<String>)

To close the File once we are finished writing to it, we must use the Close methods of both the StreamWriter and FileStream objects, like this:

    SWriter.Close()
   
FStream.Close()

Type the following code below the code you had previously added to the mnuSave_Click event procedure:

'Make sure the user did not click the Cancel button And
'    specified a file name for the file to be created. 
If iResult <> Windows.Forms.DialogResult.Cancel And  _
            SaveFileDialog1.
FileName.Length <> 0 Then
    'Create a FileStream object that connects to the file
    '    and opens it in create mode.
    Dim FStream As New _
        IO.
FileStream(SaveFileDialog1.FileName, _
       
IO.FileMode.Create)
    'Create a StreamWriter object for the FileStream to
    '    make writing to the file easy.
    Dim SWriter As New IO.StreamWriter(FStream)
    ‘Write the contents of the txtEnter textbox to the file.
    SWriter.Write(txtEnter.Text)
    ‘Close the StreamWriter and FileStream.
    SWriter.Close()
    FStream.
Close()
    ‘Destroy the StreamWriter and FileStream objects. 
    SWriter = Nothing
    FStream
= Nothing
End If

Using an OpenFileDialog control to help you read from a file

The only significant difference between the OpenFileDialog and SaveFileDialog controls is that the text on the button of the OpenFileDialog says Open and the text on the button of the SaveFileDialog says Save.   Add the following code to the mnuOpen_Click event procedure to display an OpenFileDialog:

Dim iResult As DialogResult
'Assign the dialog’s Title property
OpenFileDialog1.Title = "Choose a File to Open"
'List files with a .txt extension only.
OpenFileDialog1.Filter = "Text File (*.txt) | *.txt"
'If the user types a filename the .txt extension is added
'    automatically if they don't include it.
OpenFileDialog1.AddExtension = True
‘The InitialDirectory property lets you specify the start up
'    directory that is displayed when the Open dialog first opens.
OpenFileDialog1.InitialDirectory = "C:\"
'Clear the FileName property of OpenFileDialog1
OpenFileDialog1.FileName = ""
'The ShowDialog method displays the Open dialog.  Any
'    code that follows this line of code will not be executed
'    until the Open dialog is closed.
iResult = OpenFileDialog1.ShowDialog()

The OpenFileDialog has no OverwritePrompt property since the user is picking a file to be opened, not saved.

Creating a IO.FileStream object to read from a file

The FileStream object that we'll need to read from a file will be created exactly the same way we constructed the FileStream object to write to a file, except for the FileMode parameter.  Instead of using IO.FileMode.Create, we will use IO.FileMode.Open, like this (do not type the following code yet):

    Dim FStream As New _
        IO.
FileStream(
<File Name>, IO.FileMode.Open)

Instead of a StreamWriter which lets us write to a FileStream, we need to create a StreamReader so that we can read from a FileStream:

    Dim SReader As New IO.StreamReader(FStream)

Now, reading the contents of the file into the Text property of the txtView textbox is easy with the ReadToEnd method of the StreamReader, like this:

    txtView.Text = SReader.ReadToEnd()

Type the following code below the code you had previously added to the mnuOpen_Click event procedure:

'Make sure the user did not click the Cancel button
'    And specified a file name for the file to be created. 
If iResult <> Windows.Forms.DialogResult.Cancel And  _
            OpenFileDialog1.
FileName.Length <> 0 Then
    ‘Create a FileStream object that connects to the file and
    '    determines how the file is opened.
    Dim FStream As New _
       
IO.FileStream(OpenFileDialog1.FileName, _
        IO.FileMode.Open
)
    ‘Create StreamReader object for the FileStream to
    '    make reading from the file easy.
    Dim SReader As New IO.StreamReader(FStream)
    ‘Read the contents of the file into the txtView textbox.
    txtView.Text = SReader.ReadToEnd()
    ‘Close the StreamReader and FileStream.
    SReader.Close()
   
FStream.Close()
    ‘Destroy the StreamReader and FileStream objects. 
    SReader = Nothing
   
FStream
= Nothing
End If

Testing the program so far

Before testing the project, click on the Save All button on the toolbar to save it.  Now run the program and type something into the Enter Text textbox, and save it to a file with the Save menu item.  Then use the Open menu item and open the file so that it is displayed in the View Text textbox. 

That almost completes this project. What about the New menu item? What should it do? Try to figure out the code for the New menu item on your own.

Hints for the implementing the New menu item

  1. When prompted to save, the user explicitly selected the No button on your message box.
  2. When prompted to save, the user selected the Yes option and saved the contents of the Enter textbox to a file.
  3. The contents of the Enter textbox had not been modified since it was last saved.

To copy a Project folder from your Projects folder on the Hard Drive to a floppy diskette or pen-drive follow these steps:

  1. Exit Visual Studio 2008 and insert the floppy diskette or pen-drive, that you want to copy the Project10-11 folder to:
  2. Select the My Documents item on the Start Menu to open the My Documents folder.
  3. In the My Documents folder, double-click the Visual Studio 2008 folder to open it.
  4. Double-click on your Projects folder to open it.
  5. Open the Project10-11 folder by double-clicking on it.  Inside the Project10-11 folder, delete the Obj and Bin folders—these folders are created automatically when you open a project.  You do not need to copy them, or their contents, to your floppy diskette or pen-drive.  Important: Be sure not to delete the My Project folder or Resources folder, if it exists.
  6. Once you have deleted the Obj and Bin folders, hit the Backspace key once—or click the Back button on the toolbar.  This moves you from inside the Project10-11 folder to back inside your Projects folder.
  7. Right-click on the Project10-11 folder and selected: 31/2" Floppy A: or your pen-drive on the Send To fly-out menu.  This copies the Project10-11 folder to your floppy diskette or pen-drive.