Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
226
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Appendix D

The second part of this exercise requires you to declare two String variables, set their values, and concatenate the variables and display the results in a message box. The String variables can be declared and set as:

‘Declare variables and set their values Dim strOne As String = “Visual Basic “ Dim strTwo As String = “2005”

To concatenate the variables and display the results, you could write code such as:

‘Concatenate the strings and display the results

MessageBox.Show(strOne & strTwo, “Exercise 1”)

Exercise 2

This exercise requires you to display the length of the string entered into a text box and then to display the first half of the string and the last half of the string. To display the length of the string, you can use the Length property of the Text property of the text box as shown here:

‘Display the length of the string from the TextBox MessageBox.Show(“The length of the string in the TextBox is “ & _

TextBox1.Text.Length, “Exercise 2”)

To display the first half of the string, you need to use the Substring method with a starting index of 0, and for the length you use the length of the string divided by 2, as shown here:

‘Display the first half of the string from the TextBox MessageBox.Show(TextBox1.Text.Substring(0, TextBox1.Text.Length / 2), _

“Exercise 2”)

To display the last half of the string, you again use the Substring method, but this time you simply give it a starting index of the length of the string divided by 2, as shown here:

‘Display the last half of the string from the TextBox MessageBox.Show(TextBox1.Text.Substring(TextBox1.Text.Length / 2), _

“Exercise 2”)

Chapter 4 Solutions

Exercise 1

This exercise required you to create a Select Case statement to select and display the numbers 1 through 5 from the text box on the form. The code to do this is shown here:

‘Determine which number was entered Select Case TextBox1.Text

Case 1

MessageBox.Show(“The number 1 was entered”, “Exercise 1”) Case 2

746

Solutions

MessageBox.Show(“The number 2 was entered”, “Exercise 1”)

Case 3

MessageBox.Show(“The number 3 was entered”, “Exercise 1”)

Case 4

MessageBox.Show(“The number 4 was entered”, “Exercise 1”)

Case 5

MessageBox.Show(“The number 5 was entered”, “Exercise 1”)

To handle numbers other than 1 through 5, you need to provide a Case Else statement as shown here:

Case Else

MessageBox.Show(“A number other that 1 - 5 was entered”, _

“Exercise 1”)

End Select

Exercise 2

In this exercise, you were tasked with creating two For... . . . Next loops. The first loop is supposed to count from 1 to 10 and display the numbers in a list box. The code to execute this loop is shown here:

‘Count from 1 to 10

For intCount As Integer = 1 To 10

ListBox1.Items.Add(intCount)

Next

The second For . . . Next loop should count backward from 10 to 1 and display those numbers in a list box. The code to execute this loop is shown here:

‘Count backwards from 10 to 1

For intCount As Integer = 10 To 1 Step -1

ListBox1.Items.Add(intCount)

Next

Chapter 5 Solutions

Exercise 1

This exercise required you to create an enumeration of three names and to display the member string value as well as the numeric value when a button was clicked. To create an enumeration of names, you would use code similar to this:

Public Class Form1

Private Enum Names As Integer

Norman = 1

Mike = 2

Reece = 3

End Enum

747

Appendix D

To display the member names and values from the enumeration, you would use code like this:

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click

MessageBox.Show(Names.Norman.ToString & “ = “ & Names.Norman, _

“Exercise 1”)

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button2.Click

MessageBox.Show(Names.Mike.ToString & “ = “ & Names.Mike, _

“Exercise 1”)

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button3.Click

MessageBox.Show(Names.Reece.ToString & “ = “ & Names.Reece, _

“Exercise 1”)

End Sub

Exercise 2

You were tasked with creating an application that would redimension an array, preserving its current elements and adding a new element to the array, and display the new element in a message box. To create and initialize an array at the form level with just one name, you would code like this:

Public Class Form1

Private strNames() As String = {“Norman”}

To redimension the array, preserving the existing data, you would use code like this. Notice that you use the GetUpperBound(0) method to get the upper boundary of the array and then add 1 to it to enlarge the array by one element:

ReDim Preserve strNames(strNames.GetUpperBound(0) + 1)

To add the new name from the text box, you would use code like this. Again you are using GetUpperBound(0) to determine the upper boundary of the array:

strNames(strNames.GetUpperBound(0)) = TextBox1.Text

Finally, to display the last name added to the array in a message box, you would use code like this:

MessageBox.Show(strNames(strNames.GetUpperBound(0)), “Exercise 2”)

748

Solutions

Chapter 6 Solutions

Exercise 1

For this exercise, you were required to create a Windows application with two button controls. You were to wire up the MouseUp and LostFocus events for the first button. The code for the MouseUp event should look similar to this:

Private Sub Button1_MouseUp(ByVal sender As Object, _

ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp

‘Display a MessageBox

MessageBox.Show(“The MouseUp event has been fired.”, “Exercise 1”) End Sub

And the code for the LostFocus event should look similar to this:

Private Sub Button1_LostFocus(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Button1.LostFocus

‘Display a MessageBox

MessageBox.Show(“Button1 has lost focus.”, “Exercise 1”) End Sub

When you ran this application, you may have noticed some unexpected behavior when you clicked the first button. As soon as you let the mouse button up, you saw the message box indicating that the button had lost focus, and then immediately after that, you saw the message box indicating that the MouseUp event had been fired.

What has actually happened here is that the code in the MouseUp event was fired, but the code in that event causes a message box to be displayed. In the course of seeing that code, Visual Basic 2005 has determined that the Button control will lose focus and has fired the LostFocus event, which displays the message box in that event handler first.

Exercise 2

This exercise tasked you with creating an application that has a toolbar and status bar. You were to insert the standard buttons for the toolbar, create event handlers for the Click event of each button, and to display a message in the status bar when any of the buttons was clicked. The code for the event handlers is listed here:

Private Sub newToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles newToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The New button was clicked.” End Sub

Private Sub openToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles openToolStripButton.Click

749

Appendix D

‘Update the status bar

sspStatus.Text = “The Open button was clicked.” End Sub

Private Sub saveToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles saveToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The Save button was clicked.” End Sub

Private Sub printToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles printToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The Print button was clicked.” End Sub

Private Sub cutToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cutToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The Cut button was clicked.” End Sub

Private Sub copyToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles copyToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The Copy button was clicked.” End Sub

Private Sub pasteToolStripButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles pasteToolStripButton.Click

‘Update the status bar

sspStatus.Text = “The Paste button was clicked.” End Sub

Chapter 7 Solutions

Exercise 1

The exercise required you to create a simple application that uses the OpenFileDialog and

SaveFileDialog classes.

The code for the Open button starts by declaring an object using the OpenFileDialog class:

750

Solutions

Private Sub btnOpen_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnOpen.Click

‘Declare a OpenFileDialog object

Dim objOpenFileDialog As New OpenFileDialog

The bulk of the code to display the contents of the file in your text box remains the same as the code in the Dialogs project but uses the objOpenFileDialog object versus the OpenFileDialog control:

‘Set the Open dialog properties With objOpenFileDialog

.Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”

.FilterIndex = 1

.Title = “Demo Open File Dialog” End With

‘Show the Open dialog and if the user clicks the Open button, ‘load the file

If objOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then Dim allText As String

Try

‘Read the contents of the file

allText = My.Computer.FileSystem.ReadAllText( _ objOpenFileDialog.FileName)

‘Display the file contents in the TextBox txtFile.Text = allText

Catch fileException As Exception Throw fileException

End Try End If

Since you are using an object, you need to perform the necessary cleanup to have the object you created release its resources. You do this by calling the Dispose method on your object, and then you release your reference to the object by setting it to Nothing:

‘Clean up objOpenFileDialog.Dispose()

objOpenFileDialog = Nothing End Sub

The code for the Save button starts by declaring an object using the SaveFileDialog class, and the rest of the code is pretty much the same as the code in the Dialogs project. The code at the end of this procedure also performs the necessary cleanup of your object:

Private Sub btnSave_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnSave.Click

‘Declare a SaveFileDialog object

Dim objSaveFileDialog As New SaveFileDialog

‘Set the Save dialog properties With objSaveFileDialog

.DefaultExt = “txt”

751

Appendix D

.FileName = “Test Document”

.Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”

.FilterIndex = 1

.OverwritePrompt = True

.Title = “Demo Save File Dialog” End With

‘Show the Save dialog and if the user clicks the Save button, ‘save the file

If objSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then Try

Dim filePath As String ‘Open or Create the file

filePath = System.IO.Path.Combine( _ My.Computer.FileSystem.SpecialDirectories.MyDocuments, _ objSaveFileDialog.FileName)

‘Replace the contents of the file My.Computer.FileSystem.WriteAllText(filePath, txtFile.Text, False)

Catch fileException As Exception Throw fileException

End Try End If

‘Clean up objSaveFileDialog.Dispose() objSaveFileDialog = Nothing

End Sub

Exercise 2

This exercise requires you to display the Browse For Folder dialog box with the Make New Folder button displayed and to set My Documents as the root folder for the browse operation. You start your procedure off by declaring an object using the FolderBrowserDialog class:

Private Sub btnBrowse_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnBrowse.Click

‘Declare a FolderBrowserDialog object

Dim objFolderBrowserDialog As New FolderBrowserDialog

Next, you set the various properties of your objFolderBrowserDialog object to customize the Browse For Folder dialog box. Notice that you need to use the Personal constant to have the dialog start browsing at the My Documents root folder:

‘Set the FolderBrowserDialog control properties objFolderBrowserDialog.Description = “Select your favorite folder:”

objFolderBrowserDialog.RootFolder = Environment.SpecialFolder.Personal objFolderBrowserDialog.ShowNewFolderButton = True

You then display the dialog box, and if the user selected the OK button in the dialog box, you display the folder chosen in the label control on your form:

752

Solutions

‘Show the Browse For Folder dialog

If objFolderBrowserDialog.ShowDialog = Windows.Forms.DialogResult.OK Then ‘Display the selected folder

Label1.Text = objFolderBrowserDialog.SelectedPath End If

You end this procedure by performing the necessary cleanup of your object:

‘Clean up objFolderBrowserDialog.Dispose()

objFolderBrowserDialog = Nothing End Sub

Chapter 8 Solution

This exercise asked you to complete your Menus application by adding a StatusStrip control and writing the necessary code to display a message when text was cut, copied, and pasted in your text boxes. If you followed the same basic procedures to add a StatusStrip control as you did in the Text Editor project in Chapter 6, you will have added the control and added one panel named sspStatus.

All that is required at this point is to add code to the procedures that actually perform the cut, copy, and paste operations. Starting with the cutToolStripMenuItem_Click procedure, you should have added a single line of code similar to the following:

Private Sub cutToolStripMenuItem_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles cutToolStripMenuItem.Click

‘Declare a TextBox object and set it to the ActiveControl Dim objTextBox As TextBox = Me.ActiveControl

‘Copy the text to the clipboard and clear the field objTextBox.Cut()

‘Display a message in the status bar sspStatus.Text = “Text Cut”

End Sub

And the code for the copyToolStripMenuItem_Click procedure should be similar to this:

Private Sub copyToolStripMenuItem_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles copyToolStripMenuItem.Click

‘Declare a TextBox object and set it to the ActiveControl Dim objTextBox As TextBox = Me.ActiveControl

‘Copy the text to the clipboard objTextBox.Copy()

‘Display a message in the status bar sspStatus.Text = “Text Copied”

End Sub

753

Appendix D

And finally, the code for the pasteToolStripMenuItem_Click procedure should be similar to this:

Private Sub pasteToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles pasteToolStripMenuItem.Click

‘Declare a TextBox object and set it to the ActiveControl Dim objTextBox As TextBox = Me.ActiveControl

‘Copy the data from the clipboard to the textbox objTextBox.Paste()

‘Display a message in the status bar sspStatus.Text = “Text Pasted”

End Sub

Chapter 9 Solutions

Exercise 1

The Try . . . Catch block that you add is very simple, as shown here:

Private Sub ListCustomer(ByVal customerToList As Customer) Try

lstData.Items.Add(customerToList.CustomerID & _ “ - “ & customerToList.CustomerName)

Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, “Debugging”, _

MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try End Sub

Exercise 2

Your modified Try block should look similar to the following code. When you run your project and click the Start button, you should see a message box with the message that you added to your Throw statement.

Try

Throw New Exception(“Customer object not initialized.”) lstData.Items.Add(customerToList.CustomerID & _

“ - “ & customerToList.CustomerName)

Catch ExceptionErr As Exception

MessageBox.Show(ExceptionErr.Message, “Debugging”, _

MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

754

Solutions

Chapter 10 Solutions

Exercise 1

Once you add the Implements statement highlighted as follows and press Enter, the rest of the code shown below it is automatically inserted by Visual Studio 2005 to handle disposing of your class.

Namespace CarPerformance

Public Class Car

Implements IDisposable

Private disposed As Boolean = False

‘ IDisposable

Private Overloads Sub Dispose(ByVal disposing As Boolean) If Not Me.disposed Then

If disposing Then

‘ TODO: put code to dispose managed resources End If

‘ TODO: put code to free unmanaged resources here End If

Me.disposed = True End Sub

#Region “ IDisposable Support “

‘ This code added by Visual Basic to correctly implement the disposable pattern.

Public Overloads Sub Dispose() Implements IDisposable.Dispose

‘ Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.

Dispose(True)

GC.SuppressFinalize(Me) End Sub

Protected Overrides Sub Finalize()

‘ Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.

Dispose(False)

MyBase.Finalize() End Sub

#End Region

The code modifications needed in the Main procedure in Module1 are shown in the highlighted section that follows. Even though you did not implement the IDisposable interface in the SportsCar class, it is available to this class through inheritance. Remember that the SportsCar class inherits from the Car class; thus, all of the methods available in the Car class are available to the SportsCar class.

‘Display the details of the car DisplayCarDetails(objCar) DisplaySportsCarDetails(objCar)

755