Wednesday, July 28, 2010

Progress Bar In VB.NET

In this article you will learn how to work with Progress Bar Control and Mouse Wheel event of the window form.

Create a New Project in VB.net. Drag a Progress bar control from tool box and place on form and now drag and drop four buttons on form having text  l< << >> >l. this is simple interface for this purpose.
Now write code on form load even of the form

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

        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = 100
        ProgressBar1.Value = 0

End Sub
  • Now write code on button click events.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If ProgressBar1.Value < 100 Then
            ProgressBar1.Value += 5
        End If

End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        If ProgressBar1.Value > 0 Then
            ProgressBar1.Value -= 5
        End If

End Sub


Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        ProgressBar1.Value = 100

End Sub


Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        ProgressBar1.Value = 0

End Sub

This is code for buttons now we will see how we can work with progress bar with mouse wheel scrolling. Select MouseWheel event from form1 events.Now write simple code in this event:

Private Sub Form1_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseWheel

        If e.Delta > -1 Then
            If ProgressBar1.Value < 100 Then
                ProgressBar1.Value += 5

            End If
        Else
            If ProgressBar1.Value > 0 Then
                ProgressBar1.Value -= 5

            End If
        End If

End Sub
Now in if condition you see that e.delta > -1 this is important for us when we scroll mouse one time control comes in this event and if we scroll wheel up side e.delta value will < 0 and if we scroll down side e.delta value > 0. Only remember these things in mind. Now see this condition ProgressBar1.Value < 100 we are handling the exception and also in ProgressBar1.Value > 0 because progressbar value should be in range of progressbar1.minimum and progressbar1.maximum.