Wrox Home  

Exercise Answers for Beginning VB.NET, 2nd Edition

Chapter Question
Question Answer
1 1

What Modified-Hungarian prefix should you use for a combo box? A label? A text box?

Combo boxes are given the prefix cbo. Labels are prefixed with lbl. Text boxes are prefixed with txt.

1 2

(This assumes you set the Help Filter to Visual Basic and Related.)

Open the Help System and search for MessageBox. Notice how many topics are returned. Change the Help Filter option on the My Profile screen, to No Filter. Repeat the search for MessageBox. Did the Help System return more or fewer topics?

If you search for the word MessageBox with the Help Filter setting at No Filter, you'll return many more topics than if you searched with it set to Visual Basic and Related. The drawback is that you get topics that are only relevant if you're working in C# or C++ as well. Be sure to select the right Help Filter setting for your needs.

1 3

When creating a button, how would you make the button respond to a keyboard hot key?

You can create a keyboard hot key by using an ampersand (&) in the Text property before the correct letter. To create a hot key for Cancel button, you would enter &Cancel as the Text property.

Chapter Question
Question Answer
2 1

What is camel casing?

Code written in camel casing has a hump, for example camelCasing.

2 2

What are we more likely to use — variables that store integer values or variables that store decimal values?

In day-to-day programming, we're more likely to use integer variables than decimal variables. Integers are usually used to keep track of the state of the program, whereas you'll probably find that you rarely want to perform calculations.

2 3

How do you define a variable that contains character data?

We use As String, like this:

Dim s As String

2 4

Write a line of code that multiplies n by 64, using the shorthand operator.

n *= 64

2 5

What is an algorithm?

An algorithm is a step-by-step description of how the problem that can be solved in software is going to be solved. It's the base currency of all software and good algorithm skills are essential if you want to become a good programmer.

Chapter Question
Question Answer
3 1

What are the six possible arithmetic operators that can be used with an If statement?

Equal to (=), not equal to (<>), less than (<), less than or equal to (<=), greater than (>) and greater than or equal to (>=).

3 2

How do we do case insensitive string comparisons?

The String.Compare method can be used to perform case insensitive string comparisons in an If statement. In a Select Case statement, we use ToLower or ToUpper.

3 3

What kind of loop is appropriate for iterating through items in an array?

If we have a set of objects provided in an array, we can use a For Each...Next loop to automatically loop through each item in the array.

3 4

How can we exit a loop early?

In the case of a For loop, we can use the Exit For statement. For Do loops, we can use Exit Loop.

3 5

Why is a Select Case statement useful?

A Select Case statement is useful for making decisions based on a set of possible values. It is more efficient and easier to read than using combinations of If...End If statements.

Chapter Question
Question Answer
4 1

What's the difference between a public and private member?

A private member can only be accessed by functions, methods, and properties defined on the same class. A public member is accessible to anyone consuming the class.

4 2

How do you decide if something should be a property or a method? Give an example.

A property describes something about the object, whereas a method does something to the object. On a class representing a TV, the current channel should be described as a property because it's a fact about the state of the TV, whereas if you wanted to turn the TV on you'd use a method because that's something you're doing to the object.

4 3

What is a constructor? Why are they useful?

A constructor is a block of code that gets called whenever the object is created. They are useful whenever you need the object to be in a certain state before the consumer starts using it.

4 4

What class do all other classes in .NET inherit from?

All classes in .NET inherit from System.Object.

4 5

What is overriding?

Overriding is providing a new implementation for a method or a property that already exists on the base class (the class that the new class inherits from).

Chapter Question
Question Answer
5 1

What's the general premise behind .NET?

The premise behind .NET is to create an abstraction away from the underlying operating system and processor. Microsoft's motivation for doing this is to relieve the dependence on the Windows platform itself.

5 2

What's the similarity between .NET and Java?

.NET is very similar to Java, but where as Java from day one has said "write once, run on many platforms", .NET is saying "write in many languages, run on one platform... for now".

5 3

What is the Framework Class Library?

The Framework Class Library is a vast set of classes that abstracts the various subsystems of the operating system away in to a set of easy-to-use classes that we can use in our programs.

5 4

What is interoperation?

Interoperation (or interop) is the principle of accessing software not built in .NET.

5 5

How is application code compiled in .NET?

Code is compiled from the source language into Microsoft Intermediate Language, or MSIL. When the code is executed, it is further compiled from MSIL into the native language understood by the processor.

Chapter Question
Question Answer
6 1

What is an array?

An array is a set of similar data that is held in a list. Providing an index can access individual items in this list.

6 2

What's the difference between a structure and a class?

The differences are subtle, but the two main differences are that you don't have to use the New keyword with a structure before you can use it and you cannot inherit from a structure. It's also relatively tricky to convert from one to the other once you've chosen and started using the structure/class, so it's worth choosing wisely before you write a lot of code based on it.

6 3

What's the best way to build a collection?

The best way to build a collection is to inherit a new class from System.Collections.CollectionBase and provide implementations for Add and Remove methods and provide an Item property. This approach makes working with lists of classes or structures that you build very easy for both yourself and other developers.

6 4

What is an enumeration?

An enumeration is a list, based on a simple data type such as an integer or a string that limits the values that can be stored in a specific variable.

6 5

What is a Hashtable?

A Hashtable is a way of associating a key with a value. You can build a Hashtable up by adding items and giving each item a specific key. Coming back to the Hashtable later on with a specific key will unlock the item and make it available to you again.

Chapter Question
Question Answer
7 1

What event is fired when the mouse pointer crosses over a button's boundary to hover over it? What event is fired as it moves in the other direction, away from the button?

The button's MouseEnter event is fired when the mouse pointer "enters" a control. As the mouse pointer leaves the MouseLeave event is fired.

7 2

How can we prevent our controls from being accidentally deleted or resized?

We can lock our controls to the form by using the Format / Lock Controls menu option.

7 3

What should we consider when choosing names for controls?

Controls should be named whenever you need to refer to them from code. You should choose a convention for naming, and in this chapter, we've made the control names descriptive of what the control itself does. We also prefix the name with the type of control (btnOK for example) and make sure we follow camel casing.

7 4

What's special about the toolbar and status bar controls?

The toolbar and status bar controls automatically dock themselves to an edge of the form. When the form is resized, these docked controls stay in their relative positions glued to whatever edge they're attached to.

7 5

How can you add a separator to your toolbar?

Separators are created by setting the Style property of a toolbar button to Separator.

Chapter Question
Question Answer
8 1

Explain the following terms in your own words, and give an example of how each one might be applied in the context of a simple object-oriented holiday booking application:

  • Object
  • Class
  • Property
  • Method
8 2

Explain what classes we might want to define in order to model each of the following real-world scenarios, along with the members we'd expect them to have. If there is more than one possible solution, explain what additional information we require to establish which one will be most suitable.

  • Purchasing items at a supermarket checkout
  • Enrolling on a college course
  • Maintaining an inventory of office equipment
8 3

Extend our Car example to demonstrate on the browser that the value of the object's Gear property is restricted to a range of values between -1 and +5. Explain in your own words why it's a good idea to define functionality in method overloads that relies on calling an existing version of the same method.

<%@ page language="vb" runat="server" debug=true %>

<script runat="server">

Public Class Car

  Private _Color As String
  Private _Gear As Integer

  Public Property Color As String
      Return _Color
    End Get
    Set(value As String)
      _Color = value
    End Set
  End Property

  Public ReadOnly Property Gear As Integer
      Return _Gear
    End Get
  End Property

  Overloads Public Sub ChangeGear(direction As Integer)
    If direction < 0 Then _Gear -= 1
    If direction > 0 Then _Gear += 1
    If _Gear > 5 Then _gear = 5
    If _Gear < -1 Then _gear = -1
  End Sub

  Overloads Public Sub ChangeGear(direction As String)
    If direction = "down" Then ChangeGear(-1)
    If direction = "up" Then ChangeGear(+1)
  End Sub

  Sub New()
    _color = "cold grey steel"
  End Sub

End Class

Sub Page_Load()
  Dim MyCar As New Car()
  Dim MyGear As Integer = 0
  Response.Write("<b>New object 'MyCar' created.</b>")

  Do While (MyGear = MyCar.Gear)
    Response.Write("<br />Successfully changed up to gear " & MyCar.Gear)
    MyGear += 1
  Response.Write("<br />Failed to change up to gear " & MyGear)
  MyGear -= 1
  Do While (MyGear = MyCar.Gear)
    Response.Write("<br />Successfully changed down to gear " & MyCar.Gear)
    MyGear -= 1
  Response.Write("<br />Failed to change down to gear " & MyGear)
End Sub


It's a good idea to define a method overloads so that it makes a call on the original method rather than reimplementing functionality from scratch. This guarantees a single, well-defined set of rules to govern how that method can modify the object on which it's called. If the original method definition is modified in some way, all relevant overloads will use the modified functionality without any further work required.

8 4

When you save a file using the SaveFileDialog control and the file already exists, you are prompted to replace it. If you choose Yes, does the file actually get overwritten?

Yes and no. Remember that the SaveFileDialog is merely a means to specify where the file should be saved. It does not actually save the file; we use the StreamWriter class for this. However, clicking on the Save button in the dialog when a file already exists will cause a prompt to be displayed. Clicking on the Yes button in this prompt will cause the SaveFileDialog control to return a DialogResult of OK. Then your code would overwrite the existing file.

8 5

The Font dialog has been displayed and you have chosen a font, clicked the OK button, and applied the font. When you display the Font dialog again, do you need to set the Font property to have the same font displayed that was previously selected?

No, the FontDialog control is smart enough to display the same font again. The reason for this is that the FontDialog control never goes out of scope until you end the program. However, if you created your own object and displayed the Font dialog as shown in the code fragment below, the same font that was previously selected would not be displayed:

' Declare and set a font object...
Dim objFont As FontDialog = New FontDialog()

' Show the dialog...
If objFont.ShowDialog() = DialogResult.OK Then
    ' If OK then set the font in the text box...
    txtFile.Font = objFont.Font
End If

' Clean up...
objFont = Nothing

You would need to set the Font property to the font that was previously selected before calling the ShowDialog method. The reason for this is that the Font object that we declared goes out of scope as soon as we are done with it because we set it to Nothing:

' Declare and set a font object...
Dim objFont As FontDialog = New FontDialog()

' Set the Font property before calling the ShowDialog method...
objFont.Font() = txtFile.Font

' Show the dialog...
If objFont.ShowDialog() = DialogResult.OK Then
    ' If OK then set the font in the text box...
    txtFile.Font = objFont.Font
End If

' Clean up...
objFont = Nothing

Chapter Question
Question Answer
9 1

How do you specify an access key for a menu item?

Use an ampersand in the text. For example, to specify an access key of F for the File menu, you specify the text &File. If a menu or menu item contains an ampersand in the name you need to specify two consecutive ampersands in order to not have it interpreted as an access key. For example, suppose you had the menu item Tools & Tips. In order to have the first T as the access key and the ampersand in the text displayed correctly, you would need to specify the text &Tools && Tips.

9 2

Can you specify any shortcut key that you want?

Absolutely! As long as it is in the list of shortcuts in the drop-down list in the ShortCut property. The shortcut that you assign here will be the shortcut executed for this menu item.

9 3

Can you specify checkmarks and radiochecks in a context menu?

Yes. You use the same properties as you did when you did this in the menu.

9 4

Can you create submenu items in a context menu?

Yes. When creating a context menu item, a text area appears to the right and to the bottom of the context menu item that you are working on.

9 5

Can you create as many menu items as you want?

Yes, however, keep in mind that menus should be short and to the point. If you have too many menu items, it will be hard to locate the correct menu item. You should consider splitting a long menu into two or more separate menus.

Chapter Question
Question Answer
10 1

What's the advantage of using a class library?

The advantage of a class library is that objects, and therefore the functionality encapsulated within them, can easily be reused in other applications. All we have to do is build the classes in a separate library (or move them from existing projects into new class libraries) and include references between library and application.

10 2

In our Favorites Tray application, why did we create a new class that inherited from System.Windows.Forms.MenuItem?

The menu items we added had to know which WebFavorite instance they related to in order that Internet Explorer could be told to open the proper URL. Creating a new class inherited from MenuItem means that we can add a new property for storing the WebFavorite instance.

10 3

Why do we create our own collections?

When a developer wants to work with our classes, it's useful to have a separate class optimized for moving around lists. Creating a new class inherited from System.Collections.CollectionBase and adding a few properties makes this very easy for them.

10 4

How much time usually elapses between an object no longer having references and the Garbage Collector cleaning it up?

Trick question! There is no way to determine the time that will elapse between the final reference to an object being released and the object being cleaned up by the Garbage Collector.

10 5

What is the difference between Dispose and Finalize?

The Dispose method should be called by the consumer as soon as the resources used by the object are no longer required. The Garbage Collector automatically calls the Finalize method.

Chapter Question
Question Answer
11 1

How do you know when you receive a syntax error in your code?

The Visual Studio.NET development environment will underline syntax errors caused by improper use of methods and properties of objects and for variables not declared when the Option Explicit option or statement is turned on. Option Explicit is turned off by default.

11 2

We know that we can set a breakpoint with a hit counter, but can we set a conditional breakpoint?

Yes. To set a conditional breakpoint, click on the line of code where you want the breakpoint (such as a variable) and then click on the Debug | New Breakpoint menu item to invoke the New Breakpoint dialog. In the New Breakpoint dialog, click on the Condition button to invoke the Breakpoint Condition dialog and enter the condition in which you want the breakpoint activated. For example, to break when the intLineCount variable is equal to 5, enter intLineCount = 5 in the Breakpoint Condition dialog.

11 3

What information does the Locals window show?

It shows all variables and objects "visible" to the current function or procedure executing, and allows you to change these values.

11 4

If you are stepping through your code line-by-line, how can you bypass stepping through the code of a called procedure?

Click on the Step Over icon on the Debug toolbar or click on the Debug | Step Over menu item.

11 5

Can you define multiple Catch blocks in structured error handling?

Yes. You can test for specific errors as shown in the code below:

    intX = 1
    intY = 0
    intResult = intX / intY
Catch e As DivideByZeroException
    error handling code here
Catch e As OverflowException
    error handling code here
    code here always executes
End Try

Chapter Question
Question Answer
12 1

What is a pixel?

A pixel (or picture element) is a tiny square. Pixels are grouped together into bitmaps whereupon a programmer can set the color of each pixel individually in order to build up a picture.

12 2

What object do we need in order to draw on a control, form or other object?

Whenever we want to draw with .NET, we need to be given a System.Drawing.Graphics object. This object exposes most of the methods we need in order to draw shapes and images.

12 3

Describe the two-phases of painting in Windows.

Whenever a "thing" in Windows (control, form, menu, whatever) needs painting, it is invalidated. Windows knows which windows are invalidated and which ones need drawing. In the first phase, the invalid area is erased. In the second phase, we get the opportunity to paint our user interface.

12 4

What is the difference between client coordinates and screen coordinates?

Client coordinates do not change when the user moves the form around on the desktop. Our client area always starts at (0,0) irrespective of where the form is on the screen. Screen coordinates on the other hand describe any point on the screen, starting at (0,0) in the top-left.

12 5

How can we create Color objects with .NET?

System.Drawing.Color objects come from a number of sources. We can either use shared properties on the Color object to get hold of common system colors, for example Color.Blue or Color.Red. Alternatively, we can use Color.FromArgb and provide a red component, a blue component and a green component to make up any color that we wish. Finally, we can use the SystemBrushes and SystemPens classes to get hold of brushes and pens used for painting in the user-defined Windows user interface object colors.

Chapter Question
Question Answer
14 1

How do we define an event called SomethingHappened in a user control?

At a minimum, an event should be defined by:

Event SomethingHappened(ByVal sender As Object, _
  ByVal e As System.EventArgs)

However, an event can have any number of additional parameters.

14 2

What keyword is used to fire (or raise) an event?

To raise an event, you use the RaiseEvent keyword, and supply the event that you want to raise along with values for the event parameters. For example, to raise the SomethingHappened event, we'd write something like this:

RaiseEvent SomethingHappened(Me, New System.EventArgs)

14 3

How does a control know if it's design time or run time?

A control has a property called DesignMode, which is True if the control is in design mode and False if it is in run mode.

Chapter Question
Question Answer
15 1

Do you have to prefix the field name with the table name as shown in the following SQL SELECT statement?

SELECT Customer.[Customer Name]
FROM Customer

No. You only need to prefix the field name with the table name when selecting data from multiple tables and the tables contain the same field names.

15 2

How do you sort the data in a DataGrid control after it has been displayed?

Once the DataGrid is displayed, simply click on the column header of the column that you want sorted to have the data sorted in ascending order. Clicking on the same again will sort the data in that column in descending order.

15 3

How do you populate the DataSet component with data?

Use the Fill method of the OleDbDataAdapter as shown in the following code fragment.


15 4

What two properties of the DataGrid control must be set in order to have data bound to this control?

You need to set the DataSource and DataMember properties in order to bind data to the DataGrid control.

15 5

What are the two items that we have seen that are required by the OleDbDataAdapter?

An OleDbConnection component and a SQL SELECT statement to retrieve data.

Chapter Question
Question Answer
16 1

When is it better to use a DataView object over a DataSet object?

When you need just a subset of data from the DataSet object or you need the ability to sort or search for data in the DataView object.

16 2

When using the OleDbCommand object, you set the CommandText property to a SQL string to be executed. Can you use a stored procedure instead of a SQL string?

Yes. You simply need to specify the stored procedure name and set the CommandType property to indicate that the CommandText property contains a stored procedure as shown in the following code fragment:

objCommand.CommandText = "usp_sel_authortitles"
objCommand.CommandType = CommandType.StoredProcedure

16 3

What do the question marks in the following SQL string represent?

objCommand.CommandText = "INSERT INTO titles " & _
  "(title_id, title, type, price, pubdate) " & _
  "VALUES(?,?,'Demo',?,'" & DateTime.Now() & "');" & _
  "INSERT INTO titleauthor (au_id, title_id) VALUES(?,?)"

The question marks represent placeholders for data that will be inserted by the Parameters in the Parameters collection.

16 4

When binding a control, is it necessary to first clear the binding as shown in the following example?

txtLastName.DataBindings.Add("Text", objDataView, "au_lname")

No. This is only necessary if the control has been previously bound as was done in the Binding Example program.

16 5

The CurrencyManager object is used to control the navigation of records in a DataSet or DataView object. Can the BindingContext object also be used?

Yes, the BindingContext object can also be used as shown in the following code fragment:

Me.BindingContext(objDataView).Position += 1

Remember that the BindingContext object is built into every Windows form and contains a collection of CurrencyManager objects. We can directly access any object by specifying the object name as shown in the code fragment above.

Chapter Question
Question Answer
17 1

Does the System.Data.SqlClient namespace provide the same functionality as the System.Data.OleDb namespace?

Yes. It also is optimized for use with SQL Server and can only be used with SQL Server versions 7.0 and 2000.

17 2

How do Web Server controls differ from HTML controls?

Web Form controls provide a more feature rich object model and can be programmed at the server. This allows us to bind data to these controls and to also use VB code, which we are most familiar with.

17 3

Can HTML controls also be programmed at the server?

Yes and no. HTML controls cannot be programmed at the server. However, HTML controls can be converted to HTML Server controls by right-clicking on the control while in Design mode and choosing the Run As Server Control from the context menu. This will convert the "pure" HTML control to a server-side control, which can be programmed against at the server.

17 4

What does the IsPostBack property do?

The IsPostBack property returns a True/False value indicating whether the page has been posted back from a client request or whether the page is being loaded for the first time.

17 5

Can we mix the code that we use? For example, can we write server-side code in a form class and also write server-side code in a script block in the HTML?

Yes. However, remember that if you want to write code in a server-side script block that is for an event for a control, that you must specify the event in the control and then specify the procedure name that should be executed.

The example control below specifies the procedure to be executed when the OnClick event is fired. When you click on the button in a form, the form will be posted back to the server and the procedure Button1_Click in server-side script will be executed:

<asp:Button id=Button1 runat="server" Text="Server-Side" OnClick=Button1_Click>

Chapter Question
Question Answer
18 1

What does XML stand for?

eXtensible Markup Language

18 2

What is XML primarily used for?

XML is an open standard that's primarily used in software integration. It allows an application vendor to define its own text-based format for data that can be transferred around the network and Internet and, with a little cooperation, be easily understood by third parties.

18 3

What kinds of data can XmlSerializer work with?

XmlSerializer ultimately wants to work with simple data types, like strings, integers, Booleans, and doubles. It can work with complex structures and classes, providing that each of the properties it tries to work with ultimately ends up as a simple type.

18 4

How do you stop XmlSerializer working with a property that it might otherwise try and serialize?

By putting the System.Xml.Serialization.XmlIgnore attribute before a property or public member variable, you can tell XmlSerializer not to bother trying to work with the property.

18 5

Which class can be used to iterate through an XML document one node at a time?

System.Xml.XmlTextReader is the object that we used to work through an XML document node-by-node.

Chapter Question
Question Answer
19 1

What's the difference between a Web site and a Web service?

A Web site is designed to be used by a human being. A Web service is designed to be used by a piece of computer software.

19 2

What is SOAP?

SOAP, or Simple Object Access Protocol, is the open standard that defines how Web services and client applications exchange information. Requests are made of the Web service through a SOAP request document, which is an XML document transferred over a Web server like Microsoft IIS. When the service wants to return a value, it's packaged in another XML document called a SOAP response document.

19 3

How do we mark a method as being available on a Web service?

To mark a method as being available on a Web service, we use the WebMethod attribute at the beginning of the method definition.

19 4

What kinds of information can we return from a Web service method?

We can return all kinds of information from a Web service, including simple values and arrays of simple values. If we want to return a set of information (such as customer record, or information about a picture), we can package the results as a separate structure or class.

19 5

What's unusual about the way the Internet Explorer control is used in Windows forms?

There is no .NET version of Internet Explorer because Microsoft hasn't got round to porting it from COM to .NET technologies. When we want to use the Internet Explorer control in our applications, we have to use the COM interoperability layer. Luckily, Visual Studio does this for us, so if we want to use any old COM controls in our project we just have to add them to the Toolbox.