Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Simple Steps in VB.NET. Part 3 - Address Book 2
Simple Steps in VB.NET. Part 3 - Address Book 2
by George Poth | Published  06/05/2003 | .NET Newbie | Rating:
George Poth

I have been teaching English in Brazil since 1994 and always wanted to do more for learners than common textbooks can offer. This started with web sites that couldn't reach most students as computers and the Internet are not standard for most people in this country.

Computer tools to help Brazilian students learn a complex language like English are practically non-existent and so I sent some suggestions to software companies. Since Brazil is neither a target market for English textbooks nor for software of this kind, the rejection seemed natural.

As a result, I tried some free developer tools such as Borland's free C++ compiler, Free Pascal, and Envelope's Visual Basic. Envelope's Visual Basic, which is a Microsoft Visual Basic 1.0 clone and still available, suited my taste but I knew it was obsolete technology. In March 2003, I bought a copy of Microsoft Visual Basic .NET Standard and have been hopelessly contaminated with the programming virus ever since.

I mostly write programs for educational purposes. Having discovered the wonderful world of DirectX recently, I am diving into the most entertaining part of programming: games. One can connect teaching with pure entertainment, learning, and culture.

 

View all articles by George Poth...
Simple Steps in VB.NET. Part 3 - Address Book 2

Article source code: ssteps3_addressbook2.zip

The address book we started in Part 2 is already fully functional, but some things should be improved. Run the program and press the tab-key several times while observing the textboxes and the buttons. You will see that each time you press that key another textbox or button gets the focus. When a textbox is focused, a user can type into it without clicking it. When a button is focused, a user could simply press Enter to execute the action for which the button was made. Our tab-key works, but not quite as a user would expect it. That's why we are going to make some changes.

We have made the ID-textbox read-only. A user can't modify the content, so why would he/she go there using the tab-key? Think sharp! And if you ever get the answer, let me know. Since I can't think of a good reason, I will simply disable the tab-key for this item. To do so, go to the properties window and set the tab-stop property to false. The ID-textbox will be ignored from now on when you press the tab-key in the running program.

The tab-key should work with all other textboxes because the user is supposed to enter data. We have to rearrange the tab-indexes so that each time you press the tab-key, the next textbox gets the focus. You can change the tab-index number in the properties window, right above the tab-stop property. Change the numbers as shown in the table. Make sure you click each item before you try to change things.

Tab-Stop NumberItem
0editName
1editSurname
2editStreetAddress
3editZipCode
4editState
5editPhoneNumber
6editEmail

The tab-key also works with the buttons. For the sake of simplicity, disable the tab-key for all the buttons. It works the same way as you did with the ID-textbox. Don't think I'm sloppy. Many of you might think that setting the tab-key for the buttons is very simple, but believe me, it's not. They can be very useful when planned carefully. They can also easily become a pain in the - aw, I'm sure you know where - when you just put them there to show off. It would take more time to go into this, so let's have that in a later article. When you're done with the tab-indexes, run your program and see that it has improved a lot with these simple changes.

Speaking of changes, all programs have an icon, and ours? Yuh, okay, we have that blue-blah-blah standard application icon, and we have that primary-color-I-wish-you-weren't-there-anymore standard icon in the title bar. For those who like changes, I have included a different icon in the bin folder of the program. The icon comes from a web and lets us use it for non-commercial purposes. Sorry, but I won't advertise this web here because that's not my job.

To change the icon in the title bar, go to the properties window and find the property "Icon". Click the icon once so that the ellipsis appears. Then click the ellipsis and browse for your icon. Finally, click the icon. Wow, it's changed!

The application icon is the icon that would appear in the users menu if you installed the program on a computer. Changing the blue-blah-blah application icon is equally easy. In the Solution Explorer, right-click Addresses and choose Properties. In the Addresses Property Pages window, click Build in the left pane. You will see our old friend in the window, the blue-blah-blah application icon. Click the ellipsis on the left, next to the drop-down box which reads Default Icon. Browse for your icon as you did before and click it. You must build your program before you can see the change. When you have built it, open the folder of your program, the Debug folder, and see that the standard application icon has gone.

In Part 1 (The Button), we used tool tips, remember? Tool tips are those small yellow messages that pop up when the mouse goes over an item. Let's use them again. Just repeating what we've already learned would be dull, wouldn't it? How about multiple-line tool tips?

From the toolbox, insert tool tips. I hope you remember how that works. If you don't, feel free to review that part. It's not necessary to rename this item because we have only one. My habit is - I know, I have a lot of them - to rename everything to something very, very short, but it must remain easy to identify. I renamed my tool tips from ToolTip1 to msg. Why? I'm very, very lazy. I believe it's easier to type "msg" in each line than "ToolTip1".

Before you start writing your tool tips, you should change the property AutoPopDelay. Change the value from 5000 to 15000. This will display our tool tips for fifteen seconds instead of only five. You won't believe it: most programmers don't even bother to check this item although they have fifteen lines - or more - of tool tips. So after five seconds you're supposed to have read those fifteen lines. Ah, yes, and always check your text for spelling mistakes; they can make a horrible impression on some users.

Make sure you write each tool tip as one line. The code you see displayed here must fit the page, so it's impossible to reproduce it as it should actually look in your code. If you're in doubt, have a look at my updated sample. In part 1, I have intentionally not used multiple-line tool tips because these require more attention from you. It's very easy to get an error due to something as simple as an empty space. Observe these empty spaces when you write the code.

Private Sub DataForm1_Load(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles MyBase.Load

    'textbox tooltips:
    msg.SetToolTip(editID_
        "This number is generated automatically." & _
        Microsoft.VisualBasic.ControlChars.CrLf & "You can't change the " _
        & "input.")
    msg.SetToolTip(editName"Type the person's first and middle name here.")
    msg.SetToolTip(editSurname"Type the person's family name here.")
    msg.SetToolTip(editStreetAddress"Type the street address here.")
    msg.SetToolTip(editZipCode"Type the zip code here.")
    msg.SetToolTip(editState"Type the state here.")
    msg.SetToolTip(editPhoneNumber"Type the phone number here.")
    msg.SetToolTip(editEmail"Type the e-mail address here.")

    'button tooltips:
    msg.SetToolTip(btnLoad_
        "Click to load the database." & _
        Microsoft.VisualBasic.ControlChars.CrLf & "No changes can be made" _
        & Microsoft.VisualBasic.ControlChars.CrLf & "before the database " _
        & "is loaded.")
    msg.SetToolTip(btnAdd"Click here before you add data.")
    msg.SetToolTip(btnUpdate"Click here to update/save data.")
    msg.SetToolTip(btnCancel"Click here to reject the last changes.")
    msg.SetToolTip(btnCancelAll"Click here to reject all changes.")
    msg.SetToolTip(btnDelete"Click here to delete the visible entry.")
    msg.SetToolTip(btnClose"Click here to close the program.")
    msg.SetToolTip(btnNavFirst"Displays the first entry.")
    msg.SetToolTip(btnNavPrev"Displays the previous entry.")
    msg.SetToolTip(btnNavNext"Displays the next entry.")
    msg.SetToolTip(btnLast"Displays the last entry.")

End Sub

Each time you type & Microsoft.VisualBasic.ControlChars.Crlf &, you actually start a new line. This also works with message boxes, as we will see later today.

We still have Form1 which we are going to use to inform the user about you. The first thing we have to do is to display this form. Let's use a menu to do so. If you now thought of a menu from the restaurant, you certainly need a bit more imagination. In the toolbox, double-click the item MainMenu. The menu will appear in the upper left of the form with the text "Type Here". Click the text and type Help. Press Enter and type About. Click an empty space in the form to see your menu. Click the menu, then double-click About and edit the code so that it looks like this one:

Private Sub MenuItem2_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles MenuItem2.Click
    '"about" is the descriptive name of our form.
    'Form1 is the object.
    Dim about As New Form1()
    about.Show()
End Sub

To see if we got it right, build and run the program and click the menu to open Form1 (About). When the form comes up, it should be clear that there are some things we should change. Close the program and make the necessary changes. To display Form1, double-click Form1 in the solution explorer. You should be consistent with your colors, so consider giving it the same color as your DataForm1. The appropriate title could be "About". You should also check the startup position and the icon.

There's no reason why someone would want to resize, minimize, or maximize this form, so let's change those properties, too. In the properties window, find the property FormBorderStyle. Change this property to FixedSingle. Your form can't be resized anymore with this choice. It's a good idea to try all properties so that you know what effect they will have. To see the effects, you have to build and run the program. Maybe you prefer to set a different property. Next, find the properties MinimizeBox and MaximizeBox and set their properties to false. Your form now can't be minimized or maximized anymore. If you prefer, do the same with DataForm1.

Insert a button into Form1 and rename it to btnClose. You could also change the text property to Close, but let's do that in a different way. Double-click the form and edit the code to the following:

Private Sub Form1_Load(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles MyBase.Load
    btnClose.Text = "Close"
End Sub

Now go back into design view. You will see that the text has not changed. Build and run the program, click the menu item About, and see what happens. Ah-hah! The correct text is displayed. You can change the text property for all items within the code. For example, if you have a label named Label1 and you want to change the text to "Hi, everybody!" you just write Label1.Text = "Hi, everybody!". The advantage is that it's much faster if you have lots of items. The disadvantage is that you can see the text only when you run the program. I personally prefer to set the text in the properties window so I can see it all the time. It's slow, but I have already messed up once in a very large program, so I'm more careful now.

Double-click the button and write the code so that it closes the form. Remember that I told you that many ways lead to Rome? I also told you that there can be differences in codes which apparently do the same thing. Now we are going to learn one big difference. Look at the codes and the comments:

1. This code will close Form1:

Private Sub btnClose_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles btnClose.Click
    Me.Close()
End Sub

2. This codes will close the program:

Private Sub btnClose_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles btnClose.Click
    End
End Sub

An empty form with just a button is not very informative. Today, we will limit the information on this form to one link to your e-mail address, and if you have, one link to your homepage.

Insert two link labels from the toolbox and rename them to something meaningful. I renamed LinkLabel1 to emaillink and LinkLabel2 to hplink. Decide what text you want to use. I used Mail Me! for the emaillink and Visit my homepage for the hplink. Again, you can do this within the code if you prefer, right below the property for the button.

Double-click your e-mail link and edit the code so that it looks like this one:

Private Sub emaillink_LinkClicked(ByVal sender As System.Object_
    ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgsHandles _
    emaillink.LinkClicked
    'set this property to true if you want the color to change
    'after the user clicks the link.
    emaillink.LinkVisited = True
    'Open an empty email. Make sure you write "mailto:" before
    'your e-mail address.
    System.Diagnostics.Process.Start("mailto:georg@teleon.com.br")
End Sub

Go back to design view and double-click your homepage link. Now let's edit the homepage link:

Private Sub hplink_LinkClicked(ByVal sender As System.Object_
    ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgsHandles _
    hplink.LinkClicked
    emaillink.LinkVisited = True
    'Make sure you type http: before the address. If you don't
    'it won't work.
    System.Diagnostics.Process.Start("http://www.devcity.net")
End Sub

You can test the links right from the code, just click them. If you just copy and paste the code, change at least my e-mail address. Otherwise I might get e-mails intended for you. That would not be the first time that this happens. Of course, devCity isn't my homepage, but it's a good idea where programmers could go. When you're through with that, build and run your program again and click the links.

There's another thing that bothers me. The font size is too small for my taste. If you feel the same, do the following. In design view, click each link label once and go to the properties window. Click the property Font and then the ellipsis. Change the font and/or size and/or appearance to what you think is best. In my example, I just put the default font to size eleven and the appearance to boldface. Just remember to resize your labels so that everything is completely visible.

Now let's do something many beginners are just itching to know how that works. Open the Debug folder of your program and right-click your program. Choose "Properties" and click the Version-tab. When you click each item you will see that there's almost no information. We can change that, too. Go back to your program and double-click "AssemblyInfo.vb" in the solution explorer. Type your information, but make sure that you type within the inverted commas (""). The edited parts of the assembly info could look like this:

<AssemblyAssemblyTitle("My Address Book")>
<AssemblyAssemblyDescription("This is my first program.")>
<AssemblyAssemblyCompany("Joe Blow and his mighty VB .NET")>
<AssemblyAssemblyProduct("The Address Book")>
<AssemblyAssemblyCopyright("Me, who else?")>
<AssemblyAssemblyTrademark("C'mon, I don't have that yet.")>
<AssemblyCLSCompliant(True)>

<AssemblyAssemblyVersion("1.0.0.0")>

Build the program and look at the version information again. Now it looks quite like a professional thing, doesn't it?

Before we end today, let's talk about error handling. As I told you, I won't deal with it yet because there are some things you should learn before this. I didn't say, though, that I wouldn't introduce you to the basic concepts of error handling.

Basically, error handling is supposed to deal with all kinds of potential errors. For example, a user might give wrong input, like text where the user should provide numbers. If you haven't prepared the program to deal with the error, the user will get an error message. Other things you have to prepare your program for are accidents. This could be a simple click that closes the program although the user didn't intend to do so. The accidental click is the easiest thing to fix; just put in a message box.

Let's have look at the "Close" button. The only thing that could go wrong here is an accidental click. The result, however, would be a disaster; the user would lose all data that wasn't saved. We must provide a security device so that this will become more difficult to happen. This security device can be a simple message box. Double-click the "Close" button and edit the code so that it looks like this one:

Private Sub btnClose_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles btnClose.Click
    If MessageBox.Show_
        "Make sure you save your data" & _
        Microsoft.VisualBasic.ControlChars.CrLf & "before you close the " _
        & "program." & Microsoft.VisualBasic.ControlChars.CrLf & "Do you " _
        & "really want to exit?""My Address Book"_
        MessageBoxButtons.YesNo_
        MessageBoxIcon.Exclamation= DialogResult.Yes Then
        End
    End If
End Sub

When you now click to close the program, the message box will pop up and ask for confirmation. If the user clicks "yes", the program will close, if the user clicks "no", the user can return to the program and make any necessary changes. The way we did it is certainly not the best way, but it is merely meant as an introduction. That's why there isn't much of explanation to that code. The best solution here would be a code that saves all data before closing the program. Although we have a message box, many happy clickers don't even care about message boxes. Real error handling code is much larger. You will see in the future that programs can consist of more error handling code than program code.

Who knows, maybe you want to expand the basic things you have just learned about error handling to make some fun handling. Huh? What's that? You know, VB .NET is very patient; it let's you insert as many message boxes as you have fingertips to type. You could do this on All Fool's Day, for those people who mean soooo much to you.

No matter which button you click, you have to go through all of them. Ah, yes, just stop inserting messages boxes when your fingertips start bleeding, okay? Before the next All Fool's Day, we will have a real fun program working, I promise you. By the way, you already have the knowledge to make such a fun program, but I will leave that for later; I like the A-ha!-effect. Now you got curious, didn't you? One more reason to stay tuned to devCity.

One more thing to that: don't exaggerate. And since I've touched that subject: never ever use harmful code in your programs. Writing harmful code can be challenging, but it can also be easier than what you've done up to now. The following code is meant to slightly irritate some people or make them laugh, but it won't harm. After you have inserted the following code, run your program - and happy clicks! Let's double-click the Close button and edit the code:

Private Sub btnClose_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles btnClose.Click
    If MessageBox.Show("Do you really want to leave me?""Sniff-sniff"_
        MessageBoxButtons.YesNo_
        MessageBoxIcon.Question= DialogResult.Yes Then
        MessageBox.Show("Are you really sure?""More sniff-sniff"_
            MessageBoxButtons.YesNoMessageBoxIcon.Question)
        MessageBox.Show("Puh-leeze, don't go!""Much more sniff-sniff"_
            MessageBoxButtons.YesNoMessageBoxIcon.Question)
        MessageBox.Show("Last chance, honey: wanna leave?"_
            "Lots of sniff-sniff and bah"MessageBoxButtons.YesNo_
            MessageBoxIcon.Warning)
        End
    End If
End Sub

Basically, you have completed a simple program. Okay, for you real beginners out there: it certainly wasn't that simple. The program comes very close to a real user application. This is meaningful and interesting programming for beginners. Many books for beginners take you through an array of individual functions, and at the end of the book you still don't have a single useful program. This doesn't make much sense to me. Well, some things are still missing. I introduced you to the basic concepts error handling, and of course, we will use it in our program - later. Finally, we must be able to install our program on another computer, right? So, stay tuned.

Related devCity.NET articles:

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:1.8365758754864 out of 5
 257 people have rated this page
Article Score41730
Sponsored Links