http://www.developer.com/

Back to article

VB.NET Uncovered: Big Changes


October 20, 2002

Welcome back to the second part of our VB.NET tutorial - Big Changes.

If you haven't yet read the first instalment, check out Getting Started by clicking here.

I'm your host Karl Moore and today, we'll be looking at Windows Forms, a revamped version of 'forms' as we currently know them. Plus, we'll be taking a sneak geek-peek at how your code will change in the next version of Visual Basic. And boy, will it change.

So, strap in tightly and brace yourself for another whirlwind tour of VB.NET...

Windows Forms are essentially a more advanced version of forms as we know them today. And they bundle with a load of pretty cool functionality that enable you to build some darn advanced screens.

Top Tip: The name 'Windows Forms' may change by Beta Two. Microsoft haven't yet fully decided on a name. They originally christened this baby 'WinForms', then realised they'd be breaching some serious trademark turf. So, it's still in the air - prepare for change.Again.

Well, instead of boring you with a technology thesis, let's jump straight in and explore Windows Forms...

  • Launch VB.NET
  • On your Start Page, click 'Create New Project'
  • Under 'Visual Basic Projects', select 'Windows Application'
  • Change the Name and Location, if required
  • Hit the OK button

Hurrah - You're looking at a Windows Form!

Top Tip: Look at the Solution Explorer. See how the form filename is Form1.vb? All Visual Basic code - whether we're talking about forms or class modules - are stored as .vb files. The code inside that file describes what it is and does.

Now, click on Form1 and have a quick scroll through the Properties window. Ohhh, a few changes there. The Caption property is now known as Text. The Font property is broken down into Name, Size and such (hurrah!). Oh, and there's an IsMDIContainer property for building MDI apps.

Top Tip: .Caption properties have gone inVB.NET. You'll find they've all been standardised to .Text. You'll also findthat .Tag properties have disappeared.

Turn your eye to the Toolbox on the left of your screen. Click the 'Win Forms' box and stare in amazement. Well, maybe. Yes, these are all the new control toys you get to play with in VB.NET!

Scroll down that list using the down arrow near the bottom of the Toolbox. You'll find more 'intrinsic' controls than ever before. Let's meet a few.

Add a Label to Form1, the same way you would in VB6

Try changing the Font and what was previously the Caption property. No major changes yet - so use this opportunity to dab your brow.

Now VB.NET also bundles with the regular control crew; Button (aka CommandButton), RadioButton (formerly OptionButton) and GroupBox (previously Frame). Oh, and of course the TextBox, CheckBox, PictureBox, ListBox and ComboBox - which are at least a little more self-explanatory.

Try adding each of the above controls to your form and playing with their core properties

Top Tip: You'll notice the Shape control has disappeared. Uhm, yes. However you can still add pictures to your form - and 'draw in code' using something called the System.Drawing.Graphics namespace - more on this later!

In this list, you'll also find a hot bunch of controls you wouldn't usually find on the Visual Basic 6 Toolbox. For example, you'll notice the DateTimePicker, ProgressBar and ListView controls controls you'd usually have to 'bring into' your application using the Components menu.

Now have a play with any controls you think you've seen before and know what they do

Top Tip: To see how your controls look likeat runtime, press F5 to compile and launch your application - just as in VB6

In addition to all this, you'll find controls there you've never seen before. Even I don't know what hey all do - still, let's skim over a couple of the most important.

First off, there's the MainMenu control. This is essentiallythe old Menu Builder. Let's use it.

  • Add the MainMenu control to your Form
  • On your Form, click in the box that now says: Type Here
  • Type in: &File
  • Now add a few sub-items to the new File menu
  • Expand out by clicking in the 'Type Here' box to the right of 'File' - and add a number of menu
  • Press F5 to run your app and test your new menu

Top Tip: Enter a single dash to add aseparator to the menu

And you can add code to these menu items in much the same way as you would in VB6. Just double-click the item and enter your jazz in the code window. But we'll be looking at all that later.

Next up, let's look at the LinkLabel. This is a control design to look like a Web page hyperlink - by default it's an underlined blue, your mouse turns into a hand when you hover over and it changes colour upon being clicked. But it isn't linked to a Web site by default - when you click it, the code under the Click event runs.

Add a LinkLabel control to your FormHit F5 to run and test your new LinkLabel

Top Tip: Try checking out the LinkBehavior property for even more LinkLabel effects!

Elsewhere - and I personally find the ErrorProvider an exceptionally cool control. It will automatically highlight controls with an icon if a validation error occurs. Here's an example of it in use:

Also, the likes of ToolTips are handled differently in VB.NET - enter stage the ToolTip control. Plus, those Windows Open and Save dialogs are now accessible as 'intrinsic' controls.

Oh, and the TrayIcon control allows you to simplify adding your own icon and menu to the system tray. And the HelpProvider control allows you to easily implement helpfile access.

The list goes on! And alas in this tutorial, there's no time to cover them all in intricate detail - but if you are looking to find out more, check out the help.

Top Tip: Looking for assistance? Simply click the 'Dynamic Help' button just under the Properties window.

For now, let's move on to exploring a couple of the new and groovy form features...

Now this is the fun bit.

So perhaps I shouldn't have dedicated a whole page to these things they call 'Anchor' and 'Dock'... but hey, I'm feeling rebellious. Oh, what a daring nerd I really am.

Anyway, we've all been stuck in Resize Hell. And I've personally written code here at VB-World to help automatically fix the problem. But let's be realistic - it can get incredibly messy.

That's why most VB.NET controls include Anchor and Dock properties. These will help you solve all of those sticky sizing situations.

First off, the Anchor property. This forces one or more of your controls' borders to remain at a constant distance from the forms' border.

Let's take a peek at this:

  • Create a new Windows Application

Imagine you're creating a Web application and want a TextBox at the bottom of your form. You want it to stay there, stretching out with the form.

  • Add a Text Box to your form, so it looks like this:

  • Click on TextBox1 and view its Anchor property (under Layout)

By default, the control 'anchors' to TopLeft. In other words, it remains at a constant distance from the top and left sides of the form.

Let's change that:

  • Change the Anchor property so Top is unselected and Left, Right and Bottom are selected

The property text should change to 'BottomLeftRight'. This means your control will remain at a constant distance from the bottom, from the left and from the right.

  • Press F5 to run your application
  • Resize the form and bask in your glory

The Dock property is also pretty important, though not as revolutionary. It's similar to the Align property certain VB6 controls had. It forces the particular control to 'stick' to a side of the form - or with the 'Fill' option, cover the whole form.

  • Add a new Text Box to Form1
  • Experiment with the Dock property

And now, as Bush told his followers, for something completely different... <ahem>

### Visual Inheritance ###

Death, eh? Tsk! What a bummer.

Still, life's overrated I say.

But sometimes popping the ol' clogs can be a good thing, so long as (a) it ain't you, (b) the person in question leaves you a tonne of money.

That's inheritance.

Yes, oh yes, it's yet another smooth link to a technical topic. Oh yes. Ohhh yes. Bet you didn't even notice that one coming.

Now, inheritance in the above instance is where you get something, where something is added to yourself. And you're usually talking about a wad of cash.

In VB.NET, you also get inheritance. But that wad of cash is unfortunately replaced by the likes of code and Combo Boxes.

Later in this series, we'll be dealing with real code inheritance - but right now, let's look at Visual Inheritance. This is where one form 'inherits' its layout (and maybe even its code) from another'master' form.

Let's pretend you have a common set of features on more than one form. Perhaps I'm talking about a 'OK' button, a Web site hyperlink, a form backdrop, data entry TextBox controls, the layout of that Wizard -whatever common form elements you have, you can share them and their related logic with visual inheritance.

  • Create a new Windows Application
  • Add a few common elements to Form1

For my 'common elements', I've added a LinkLabel that 'anchors' to BottomRight, an 'OK' Button that anchors to BottomLeft. Oh yes - and a simple Label bearing the name of my application. And it all looks alittle like this:

Now before you can 'inherit' a form, it needs to be 'built' (sort of a mini-compile). Don't look at me, but you have to do it. Let's go:

  • From the Build menu, select Build

Next up, let's inherit that form:

  • Click Project, Add Inherited Form
  • Ensure 'Inherited Form' is selected, then click OK
  • In the list that appears, select your Form1 and click OK

  • If Form2 does not automatically appear, double-click on it in the Solution Explorer
  • Well, looky here. There's Form2 with all the features of Form1 on it.

    • Add a few TextBox controls to Form2

    Let's see Form2 in action. To do this, we'll have to change the Project Properties:

    • Right-click on your Windows Application in the Solution Explorer
    • Select Properties from the popup menu

    Your screen should look like this - if not, you've selected the wrong item in the Solution Explorer:

    Have a quick browse around. This is where you can change the Assembly name (what we used to call the 'Project' name), the version number, application icon - and hey-hey, the Startup Object. That's our stop.

    • Change the Startup Object to Form2 and click OK

    Now let's test out your inherited form:

    • Hit F5 to test your application

    Notice how it all works together? Try resizing Form2 - if you've used the Anchor properties on the inherited controls, they'll move along with the new form.

    And if you'd perhaps put code behind Form1, it'd be automatically inherited. Hmm, love that centralisation. In fact, you could even allow Form2 to 'override' certain pieces of functionality - for example, the code behind the 'OK' Button could be determined by Form2, even though the visuals come from Form1.

    If you're eager to learn more, check out the help.

    There's no doubt about it - VB.NET brings with it big coding changes.

    And every time I pen an article detailing the differences, I receive hate mail and continual ICQ harassment. In fact, I'm still trying to think of a witty response to: "I mean, why the HELL did YOU remove the Shape control?"

    So I'll admit from the start that not everyone will agree with this shift. It's a big change and, hey, nobody likes change. But once you really start to understand why these things are here and how to use themproperly, suddenly it all begins to make sense. Sorta.

    Anyway, let's try to figure it out - by venturing off into the code window:

    • Create a new Windows Application
    • Slap a new Button onto Form1
    • Right-click on Form1
    • Select 'View Code'

    Welcome to the Code Window!


    Blow Up!

    Now, you're probably already scratching that head. And if you aren't, you should be. I was darn confused by this point already.

    Where did all that code come from? And the strange answer is that you did it.

    Nope, you weren't intermittently possessed by Bill Gates, made to tap out this groovy VB.NET project with related form code, knocked on your head then forced to forgot it all by the use of hypnotic suggestion and rather large magnets. Though I guess it is remotely possible.

    But no - this is all created when you add a new Windows Form. Still, what does it all do?

    Well, it looks incredibly, incredibly weird. However at its core, this code simply describes your form.

    Remember I said that all files in VB.NET have a .vb extension? Well, VB.NET knows it's a form because all this code behind the scenes tells it so. It describes everything from the form name through to itsdimensions, through to the controls you'll find upon it.

    Top Tip: If you look through the code behind this form, you'll notice that Form1 is actually a class. From VB4 onwards, we've been able to treat forms as classes - but in reality, they neverreally were. With VB.NET, they are - and come with all the usual stuff you'll find in VB.NET classes, including Constructors and the Dispose method. More on this later.

    So that's what all the extra code is about. Boring stuff, really... just ignore it for the mo. Now, let's look at creating our own code...

    Top Tip: You can expand or hide chunks of code using the 'plus' and 'minus signs to the left of your code window. You can also define your own 'hideable' regions using the #Region statement. Check out the help for more information.

    Let's look at writing a little of our own VB.NET code now.

    To get started, first switch back to Design view.

    • Click View, Designer

    I've brought you back here so you can see that writing code for, say, a Button is just as easy in VB.NET as it was in VB6. Erm, if VB6 had Buttons. Which it didn't. But if it did, it wouldn't be difficult. Oh boy.

    • Double-click on Button1

    Dij` vu? Hello!

    Your cursor should currently be flashing in a code window between the following:

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)End Sub

    Now whatever code sits between these two lines is fired whenever Command1 is clicked.

    Top Tip: To respond to other Button events, or the events of your Form, select the Class and Method names using the combo box just above the code window. You can also fire off a separate sub in response to an event, using the Handles keyword to see the help for more information.

    Let's add some code now...

    • Add the following code to the Click event of Button1:
    MessageBox.Show("Hey... hehe... you clicked me and it tickles!")
    • Hit F5 and test your code

    OK, so maybe it's not quite the technological revolution Bill Gates promised you. But we're getting there.

    Top Tip: As we mentioned in the firstinstalment, MessageBox.Show is the new VB.NET method of displaying a messagebox. It replaces the old MsgBox statement.

    Now, you may have heard about these things called 'Namespaces' in VB.NET.

    Namespaces are a cool way of organising functionality. They're essentially a bunch of classes built into the entire .NET Framework - and every .NET programming language has access to these.

    For example, there are dozens of functions we VB developers are used to in the Microsoft.VisualBasic namespace.

    To see what I'm talking about, go to the code window and type Microsoft followed by the period (full-stop). You should be presented with two options - Win32 and VisualBasic. If you type VisualBasic and press the period once more, you'll get a list of all the functions we coders are acquainted with.

    So, if you wanted to use the StrReverse function we know from our VB6 days, you could execute a chunk of code like this:

    MessageBox.Show(Microsoft.VisualBasic.StrReverse("Karl Moore"))

    Eeeek! I hear you scream. But that's so much longer than just using the ol' StrReverse keyword we previously had. And I agree.

    First off, let me explain that this 'organising' of classes has a number of advantages. For a start, uhm, it's organised! You also avoid naming conflicts and gain a common ground throughout all languages.

    However by default, all commands in the Microsoft.VisualBasic 'namespace' are 'imported' by default, meaning you only have to use their name and can skip the Microsoft.VisualBasic prefix.

    Top Tip: A 'namespace' is imported by either specifying 'Imports Whatever.Whatever' within your form or component - or by specifying Imports in the Project Properties.

    Another Top Tip: Don't get confused when people talk about 'Imports'. It's just a way to save you typing all those lengthy prefixes. In fact, it's very much like the 'With' statement you already know and love. You do love it, don't you?

    So if we don't need to use the Microsoft.VisualBasic 'namespace' - why did I even bother to mention it? Uhm, good point. In fact, you could do a lot of your programming without even realising you'reusing namespaces.

    However it's good to know, after all, there's isn't only the Microsoft.VisualBasic namespace. There's the System namespace too ... and that beast has about a zillion commands under it. Try typing it in and you'll see what I mean.

    So - sometimes you might want to use the functionality from a namespace that isn't imported by default. And then you'll need to either 'import' it or reference it using the full 'namespace path'.

    When would you need to do this? Gee, don't look at me.

    Perhaps if you're working with graphics, you'll be interested in the System.Drawing.Graphics namespace. Or if you're manipulating databases, you'll want to peruse System.Data.ADO. Or maybe if you're looking to preserve old Visual Basic code, you'll want to check out the Microsoft.VisualBasic.Compatibility.VB6 namespace.

    Confused? You will be.

    Let's recap. Namespaces are a naming scheme to help organise the various classes available to our application. And you can access the commands of some namespaces that are 'imported' by default without having to type all those whopping great prefixes.

    Don't forget, new namespaces will step onto the scene. And although we've covered some of the most important right here on this page, your 'VB professionalism' may start to rest on exactly how much you know about the existing namespaces.

    So, you now know about namespaces. And in my mind, that is the biggest change in VB.NET.

    It's a weird concept. It's difficult to understand. It's a weird concept. Did I already say that? Well, I wanted to say it again. It's weird. Oh, and again.

    But if that has 'clicked', then hurrah! You can now do virtually everything you could back in the ol' VB6 days! And you're well on your way to becoming a VB.NET guru.

    Top Tip: At this stage, you might want to compile your test .EXE application, if only for the experience. Use the Build menu to do this - note that your .EXE will be placed in the BIN subfolder of your project.

    Next up, I'm going to run through what I deem to be the major changes to actual coding syntax. It won't make bedtime reading, but will give you a few pointers as to what to watch out for. So let's continue...

    Coding whatnots. What has really changed that you need to know about?

    Well, apart from the namespaces thang, let's review the stuff that will affect you:

    Longs, Integers - Our old Long has turned into anInteger and the Integer has turned into something called Short. The new Long inVB.NET holds a 64-bit number

    Byte, Char - The new Byte data type can hold a numberbetween 0 and 255. The new Char data type consumes 2 bytes of space and canhold one Unicode character.

    Goodbye Variants - Variants have disappeared. In itsplace is the generic Object data type, which can now hold virtually anything(it ain't as memory-intensive as VB6 neither)

    Currency Replacement - The Currency data type no longer exists in VB.NET and is replaced by the more powerful 128-bit Decimal data type

    Variant Declaration - In VB6, "Dim X, Y, Z As Integer" would result in two Variants and anInteger. Yet in VB.NET, this gives us three Integers (which, remember are our old Longs!)

    Zero-Based Arrays - This is something a lot of people have complained about and is subject to change. Arrays in VB.NET are zero-based - meaning they always start at 0. So code such as "Dim MyArray(10) As Integer" would result in an Integer array of eleven elements - zero through to ten

    Top Tip: To declare variables (+ arrays!) that have a "form-level" scope, place them before the 'New' method automatically created for you in the code window. This is the old Declarationsarea.

    UDT Changes - User-defined types are awfully useful. But when declaring in future, you need to use the API-like keyword Structure instead of Type. So here's how you would declare a sample UDT:

    Structure MyStructurePublic Name As StringPublic Age As ByteEnd Structure

    Collections Gone - VB.NET doesn't support the Collection object as we know it. Instead, it provides you with a bunch of new collection types in the System.Collections namespace - the most similar are HashTable and ObjectList. However you can use the old Collection object using the Compatibility namespace, like this:

    Dim MyCol As Microsoft.VisualBasic.Compatibility.VB6.Collection
    MyCol.Add("My Information")

    New Operators - VB.NET brings with it a few new arithmetic operators to help cut down your code. For example, "X += 4" in VB.NET will do what "X = X + 4" did in VB6. Try playing with these too: "X -= 10, X *= 2", "X /= 13", "X \=13", "X ^= 3", "X &= " OK"

    Short Circuiting - VB.NET short circuits If...Then statements. So, if you have two parts of an If...Then statement and the first returns False, VB.NET doesn't bother to look at the second part

    No Set - In VB6, we used the Set statement quite often - it was the one thing that set objects apart from any other regular data type. In VB.NET, everything is an object - so there's no need for it. If you do type it in, VB.NET currently removes it for you. How nice

    Property Declarations - Properties are now declared differently - no more separate Lets and Gets. Here's an example of a new property procedure... note that Value is now a keyword that always contains the value passed to this property.

    Public Property MachinePart() As StringSetmstrName = ValueEnd SetGetMachinePart = mstrNameEnd GetEnd Property

    Error Handling - Even error handling has changed in VB.NET. Here, you use a Try, Catch and Finally structure. The code within the Try block is run - if an error occurs, code in the Catch block is run. Whatever happens, the Finally block is always run. This is a strange concept to VB programmers yet is common practice to anyone familiar with C or Java. I recommend you use the VB.NET help index to find Error Handling, Overview - "Introduction to Exception Handling". Be sure to check out the 'Try...Catch...Finallystatement' section and test the example provided.

    Default ByVal - By default, all parameters are now passed 'by value' as opposed to 'by reference'. To be safe, make all declarations explicit

    It's No .Show - There's no longer a simple Form.Show method. Everything in VB.NET is an object - so you need to actually 'Dim FormName As New Form1', then do a 'FormName.Show'

    Control Arrays - Hasta la Vista, Guten Tag and all that, baby

    Garbage Collection - Although not a coding change, Garbage Collection is a process that runs when the operating system (slash .NET Framework) thinks it's time to clear up object references and such. So in VB6, when you set an object to Nothing, it immediately disappears from memory. However in VB.NET, this doesn't happen straight away - and your object may stay 'live' for a few minutes before being terminated by the Garbage Collector - so you can never be too sure when class termination code will run! Strange though it may seem, this 'nondeterministic finalization' does have its benefits - such as automatically correcting circular references. Check out the help for more (if you're really that interested <snore>)

    Return Keyword - Inside a function, instead of setting the function name to your return value or object, you can simply state "Return MyData" allowing you to perhaps change the function name without altering the actual code

    Top Tip: I can't hope to cover all of the syntax changes here, though hope to have presented what I deem to be the most important. To find out more on any particular subject, check the help. And of course, if you have any important additions - post a message at the feedback forum.

    Another Top Tip: - Don't forget, much of the old VB6 functionality is still available to you in VB.NET - simply refer to them via the Microsoft.VisualBasic.Compatibility.VB6 namespace. However, asever, it's better if you can move along to the newer, more generic functions.

    This week, we've taken yet another lightning VB.NET tour.

    We've covered Windows Forms, the new controls, property changes, Anchoring and Docking, plus Visual Inheritance.

    Then we moved onto namespaces and the various code changes in VB.NET, whilst continuing to learn more about the development environment. And if you have any questions, don't forget to stop by our .NET Forum.

    In the next instalment, we'll start working with the Web, with an exciting look at Web Forms. After that, we'll be looking at Web Services, ADO.NET and the Object Oriented features of VB.NET.

    There's plenty more to come - but don't forget, we can't hope to cover absolutely everything in these beta tutorials. Therefore - play, play, play! Discover, explore! Find out for yourself!

    VB.NET is a confusing tool. It's frustrating, slow and buggy. But by experimenting now, you're keeping yourself ahead of the crowd.

    So well done, my friend! I hope to see you again next week.

    This is Karl Moore signing off for tonight, wishing you a very good evening. Goodnight!

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date