Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

326 Part II Programming Fundamentals


Examine the Quick Note program code


  1. On the File menu of the Quick Note form, double-click the Insert Date command.


The InsertDateToolStripMenuItem_Click event procedure appears in the Code Editor.
You see the following program code:
txtNote.Text = My.Computer.Clock.LocalTime & vbCrLf & txtNote.Text
txtNote.Select(0, 0) 'remove selection
This event procedure adds the current date and time to the text box by linking, or
concatenating, the current date (generated by the My.Computer.Clock object and the
LocalTime property), a carriage return (added by the vbCrLf constant), and the Text
property. You could use a similar technique to add just the current date (by using
DateString) or any other information to the text in the text box.
When you insert the date using the Insert Date command, sometimes the text is
selected. To remove this selection, the Select method is called. The selection is set to
the beginning of the text box by specifying 0 in the first parameter, and the length
of the selection is set to 0 in the second parameter. This removes any selections
and positions the cursor at the beginning of the text box.


  1. Take a moment to see how the concatenation statements work, and then examine
    the SaveAsToolStripMenuItemClick event procedure in the Code Editor.
    You see the following program code:
    SaveFileDialog1.Filter = "Text files (.txt)|.txt"
    If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
    'copy text to disk
    My.Computer.FileSystem.WriteAllText(

    SaveFileDialog1.FileName, txtNote.Text, False)
    End If
    This block of statements uses a save file dialog object to display a Save As dialog
    box, verifies whether the user selected a file, and writes the value in the txtNote.Text
    property to disk by using the WriteAllText method. Note especially the statement:
    My.Computer.FileSystem.WriteAllText( _
    SaveFileDialog1.FileName, txtNote.Text, False)
    which assigns the entire contents of the text box to the file. The important point
    to note here is that the entire file is stored in the txtNote.Text property.

  2. Close the program by using the Close Project command on the File menu.


You’re finished with the Quick Note program.

Processing Strings with the String Class


As you learned in the preceding exercises, you can quickly open, edit, and save text files
to disk with the TextBox control and a handful of well-chosen program statements. Visual
Basic also provides a number of powerful statements and methods specifically designed for
Free download pdf