Wednesday, October 31, 2012

The using function in VB.NET

The using function in VB.NET


In VBA or some other programming language, you offend need to make sure you declare, create and clear an object.
Check this VBA sample (totally fake I know):

Public Sub vbatest()

    Dim oDocument As Document
    Set oDocument = New Document

    'do something here

    Set oDocument = Nothing

End Sub


But what if you want to do thing like the old fashion way. What if you want to tell exactly with to set an object to nothing?
Using Visual Studio 2010, I’ll show you 2 code samples. The first one is the simple way. The second one uses the using function.

''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        oTimer = New System.Windows.Forms.Timer
        oTimer.Interval = 1000
        oTimer.Enabled = True
        oTimer.Start()
        If oTimer Is Nothing Then
            MsgBox("oTimer is Nothing")
        End If
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class







 This is the second sample with the Using function


''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Using oTimer = New System.Windows.Forms.Timer
            oTimer.Interval = 1000
            oTimer.Enabled = True
            oTimer.Start()
        End Using
        If oTimer Is Nothing Then
            MsgBox("oTimer is Nothing")
        End If
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class




The using function makes sure your object you use is set to nothing after it leaves the End Using.
I don’t have any practical situation where you could use or not the Using function.
Please note that an Object is not necessary deleted when the function ends. In fact, never assume your object is set to nothing automatically.

The program I love to use:


Sample Code : TimerSample.zip

Tuesday, October 30, 2012

Insert a Timer without the form Designer

Insert a Timer without the form Designer


On a previous post [How to use a Timer], we show you how to use a Timer from the System.Windows.Forms.
But you could also make it without the form designer.  This gives you the advantage to control your code. Visual Basic Express or Visual Studio will always try to write your code base on the windows design form. The biggest problem is when Visual Basic is mess up and starts building garbage line or duplicate objects. It happen most the ContextMenu and StripMenus.

Typing your own code will also help you gather your stuff. Check this sample:

''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        oTimer = New System.Windows.Forms.Timer
        oTimer.Interval = 1000
        oTimer.Enabled = True
        oTimer.Start()
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class


The most important line is this one:

    Private WithEvents oTimer As System.Windows.Forms.Timer


Is important for you to place it inside your class and mostly important to put the WithEvents. The WithEvents make the oTimer1 to activate the Tick function:

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub


How you name your function is really not important. I called it timerTicks without parameters. Well in fact, in this case, it works and lucky for us. All matter is at the end of your function, your put Handle and the event of the object. In this case, is oTimer.Tick

What does this program do?


The first function initiates the oTimer1 and set some values. The interval is the period.  If the interval is a 1000, the interval is set a 1 seconds. You see? The units are in milliseconds.
Then, make sure to enable your timer. By default, is set to false. Make sure is set to true if you want the timer to work.
Finally, use the start method to start the count down.

At 1000 milliseconds, the program triggers the event and calls the function timerTicks. Inside that function, place anything you want.

In this example, I made a simple clock.

This is very interesting if you need a timer in a little code in MS-Excel or MS-Word with Visual Basic for Application (VBA). Use it for simple program too.



The program I love to use:

Sample Code :

Monday, October 29, 2012

How to use the Timer

How to use the Timer from System.Windows.Forms.Timer


There a many ways to do things. Today, let’s try to use the timer control. The timer control is more like a countdown function. Is simple and doesn’t slow down your application. In fact, it runs a new thread in background.
For this example, create a new project as a Windows Forms Applications.  Double-click the Timer from the tool box. This will insert the Timer1.
Now, the first thing you should do it to take a look at the code here.


Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Enabled = True
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        Me.Text = Date.Now
    End Sub
End Class


The first function initiates the Timer1 and set some values. The interval is the period.  If the interval is a 1000, the interval is set a 1 seconds. You see? The units are in milliseconds.
Then, make sure to enable your timer. By default, is set to false. Make sure is set to true if you want the timer to work.

Finally, use the start button to start the count down.

At 1000 milliseconds, the program triggers the event and calls the function Timer1. Inside that function, place anything you want.

In this example, I made a simple clock.

This is very interesting if you need a timer in a little code in Excel or Word. Use it for simple program too.


The program I love to use:

Sample Code : TimerSample.zip

Build a simple Timer

Build a simple Timer


There a many ways to do things. Today, let’s try to use the timer control. The timer control is more like a countdown function. Is simple and doesn’t slow down your application. In fact, it runs a new thread in background.
For this example, create a new project as a Windows Forms Applications.  Double-click the Timer from the tool box. This will insert the Timer1.
Now, the first thing you should do it to take a look at the code here.


Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Enabled = True
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        Me.Text = Date.Now
    End Sub
End Class


The first function initiates the Timer1 and set some values. The interval is the period.  If the interval is a 1000, the interval is set a 1 seconds. You see? The units are in milliseconds.
Then, make sure to enable your timer. By default, is set to false. Make sure is set to true if you want the timer to work.

Finally, use the start button to start the count down.

At 1000 milliseconds, the program triggers the event and calls the function Timer1. Inside that function, place anything you want.

In this example, I made a simple clock.

This is very interesting if you need a timer in a little code in Excel or Word. Use it for simple program too.


The program I love to use:

Sample Code : TimerSample.zip

Thursday, October 25, 2012

How to prevent value-changed events from firing on form load in VB.NET

How to prevent value-changed events from firing on form load in VB.NET



Imagine you want a MsgBox to start if someone trigger an event. When your start the code, the Msgbox is called before the form is completely loaded and likely you get an empty. Look at the code below.


Public Class Form1
   
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.
        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter

        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click

    End Sub
    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

        MsgBox(ListBox1.SelectedIndex)



    End Sub


End Class



Last post wasn’t easy to understand because I wanted to show how a ListBox works. But when the ListBox reacts incorrectly, I feel that I a have to give more details. So now, is time or never to clear things. Is very important to understand how the form is loaded. I will do my best to make it simple.




Step 1 : create the form


We have to do at least something.


Double click your form and you will get this:


Public Class Form1
   
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        

    End Sub

End Class

What you is a class and every in every class, there is a constructor. The constructor is called first, because it create the object. It creates the space in the computer. Creating the object doesn’t means the object is initialized or ready. Again, the constructor new in the class form is :

Hey! Dear computer. I need like 10 Ko of Ram to store this form right now!


Where is the new function?


Let’s be lazy and use Visual Basic Express 2012 or Visual Studio 2012 to print it for us automatically.

Place your cursor anywhere in your form class but outside a function. Go on top of your screen and click on the ComboBox with Declarations in it.



If you choose New, it will put the function at the end of your class. Whatever the function new is printed before the load form function really doesn’t matter. The new function will always be the first function.


So here is the code in the form1 class. You have form1_Load and the New function.


Public Class Form1

    Private Sub form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
End Class





Where is the InitializeComponent ?


Visual Studio or Visual Basic build a function named InitializeComponent. Inside that function, you could find all the little settings you made from the form1.vb Designer. 

Each time you place a control in the form, each time you customise the properties of your control inside that form designer, it translate them in the InitializeComponent function.

So where is the InitializeComponent ? Well... instead of telling where to find it, I’ll tell you how to find it.

Place your cursor overt the InitializeComponent, left click on it. Then press F12 on your keyboard. Visual Basic Express or Visual Studio will automatically bring you to the function definition.

And what could we find in that InitializeComponent function? Well see it for yourself. Simple settings.

So what do we have to understand? The program creates the form1 object using the new function. Then it calls the InitializeComponent inside that New function. The InitializeComponent set some general properties like size , color, and so on.

Ok, is time to move to the next step.


Step 3 : insert an event.


Alright, in the form I simply inserted and ListBox. To be honest, you could insert any control. It is really not important. Our goal here is to understand how thing works. The more you understand, the more you get better.

From the form designer, insert a ListBox. Double-click on that ListBox. Normally, your code should look like this:



Public Class Form1

    Private Sub form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    End Sub

End Class


Your cursor should be in the ListBox1_SelectedIndexChanged function. That function whatever is called is really not important. You could rename it. What is important is at the end of the function line, there is a little phrase like this:


         Handles ListBox1.SelectedIndexChanged


Please don’t try to change that part.


Monday, October 22, 2012

How to use a Listbox in VB.NET

How to use a Listbox in VB.NET


Select a Listbox from Visual Basic Express or Visual Studio’s Toolbox. Draw the frame of that ListBox and you should be ready to go. Your ListBox should be named ListBox1 if is your first one in your form.

ListBox


Then, in the code, we adjust the properties. I choose to do at the start of the form. You could do the same. I decided to do thing differently using the With function (it only change the presentation).



    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With
    End Sub


When the ListBox is initialized, we can add words in it. In the same load function, I decided to add a lot of words. Nothing complicate and obviously some are identical.


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")

    End Sub


ListBox1 is sorted alphabetically. That means all the “allo1” are all grouped together. “allo2” come after and so on. It will work each time you add a String in it.

If you execute the code right now, you will notice that no item is selected. This is perfect in most cases.


If you want to set an initial selection in ListBox1, you need to use SelectedIndex or SelectedItem.

Be careful. Each time you add an item or remove one from the ListBox, the indexes changes. Same thing if you sort an unsorted ListBox. So you can’t rely on the SelectedIndex property to get you result.


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.



You could use SelectedItem to get the String stored in the ListBox. Again, the String may not be unique, so you have to be careful. If the user chooses something in the ListBox, you have to make sure your program will deal it correctly. Please notice the programme will always stop his selection on the first encountered.


        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter




You could make the ListBox1 more interesting using the SelectionMode property.


        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click


When SelectionMode is equal to SelectionMode.MultiSimple, then the user could simply use the mouse button to selecto or deselect the items in the ListBox1.

When SelectionMode is equal to SelectionMode. MultiExtended, the user need to use CTRL or SHIFT with the mouse button to select or deselects items.


We could also introduce a little event in the ListBox1. Lets say if the user choose an item in the ListBox, a little message box pops up and display the information. Just for fun or to validate our code.

Is pretty simple with Visual Basic Express 2010 or with Visual Studio 2010. Open your form with the design view  form1.vb [Design]. Double click on your ListBox1. You should see something like this.


    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged



    End Sub



Now put a MsgBox in the function and try to display something. Like SelectedIndex.


    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

        MsgBox(ListBox1.SelectedIndex)

    End Sub


So when you change the selection in ListBox1, it will show the index (a number).

Your code should look something like this by now:


Public Class Form1
   
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.
        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter

        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click

    End Sub
    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

        MsgBox(ListBox1.SelectedIndex)



    End Sub


End Class



There is now a little flood in this code. When your start the code, the Msgbox is called before the form is completely loaded and chance are your get an empty Msgbox. This is not very sexy. We have to make this program a little more intelligent by putting a condition in the event function. Starting from now, I’ll quickly talk about it and forgive me if I am doing this too quickly. I’ll post another article later this week.