Wednesday, February 24, 2010

Multithreading in VB.NET

(This is one of the concept which I liked very much in .NET)

It gives the program to do many things simultaneously.Threading is used to divide many things at a same time but independently or dependently.

Here I will be telling in brief how threading is used in a small application using class and delegates.I will populate a listbox with numbers 0-500 bysing threads.

1) Create a windows application
2) Add a Form "FormMain"
3) Drop a button "ButtonStartThread"
4) Drop a Listbox "ListBoxNumbers"
5) Add a class "ClassDo"
6) In buttonClick write this
Private Sub ButtonStartThread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonStartThread.Click
       Dim objClassDo As ClassDO
objClassDo = New ClassDO
AddHandler objClassDo.evtdisplayInLV, AddressOf evt_hndlr_displayInLV 'Event handler to handle the event raised from the classdo
End Sub

7) Event handlers and delegates

Private Sub evt_hndlr_displayInLV(ByVal p_intVal As Integer)
'Call a delegate to handle this event.We do this to avoid cross thread operations
Me.Invoke(New del_displayLV(AddressOf hndlr_displayLV), p_intVal)
End Sub
'Declare a delegate
Private Delegate Sub del_displayLV(ByVal p_intVal As Integer)
Private Sub hndlr_displayLV(ByVal p_intVal As Integer)
'Populate the item in the listbox
End Sub
8) In class Define these things

Imports System.Threading
Imports System.Windows
Public Class ClassDO
'Declare and event to raise in the main form
Public Event evtdisplayInLV(ByVal p_intVal As Integer)
'this function is called form the main form
Public Sub startThread()
'Call a thread here
Dim objTH As Thread
objTH = New Thread(AddressOf doStuff)
End Sub
'Procedure to be called by the thread
Private Sub doStuff()
Dim intMax As Integer = 500
Dim intVal As Integer = 0
While True
intVal += 1
If intVal > intMax Then

Exit While
End If
'Sleep the thread to view the progress
'Raise and event to the main form to display in the Listbox
RaiseEvent evtdisplayInLV(intVal)
End While
End Sub

End Class

Tuesday, February 9, 2010

Dynamic button creation

Dynamic button creation in VB.NET with click events

It is simple to create a button runtime. But it is one more step to define a respective event handler for the events for the control.

Load buttons

Private Sub loadButtons()
Dim intNoOfTextBox As Integer = 10
For intC As Integer = 0 To intNoOfTextBox - 1
Dim objButton As Button
objButton = New Button
objButton.Size = New Size(200, 25)
objButton.Location = New Point(5, intC * 25)
objButton.Text = " My Runtime Dynamic Button " & (intC + 1).ToString
AddHandler objButton.Click, AddressOf ButtonClick
End Sub

Event handler for button click

Private Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim objTempButton As Button = CType(sender, Button)
Dim strButtonText As String = ""
strButtonText = objTempButton.Text.Trim
End Sub