Tuesday, January 5, 2010

How to use controls in function used by Thread

When ever we tries to use any control from thread (function used by thread) then we will get following error:
Cross-thread operation not valid: Control 'ControlName' accessed from a thread other than the thread it was created on.

Solution:
For SETTING PROPERTY VALUE for any control below code will help u out from error:
Delegate Sub SetControlValueCallback(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object)
Private Sub SetControlPropertyValue(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object)
If oControl.InvokeRequired Then
Dim d As New SetControlValueCallback(AddressOf SetControlPropertyValue)
oControl.Invoke(d, New Object() {oControl, propName, propValue})
Else
Dim t As Type = oControl.[GetType]()
Dim props As PropertyInfo() = t.GetProperties()
For Each p As PropertyInfo In props
If p.Name.ToUpper() = propName.ToUpper() Then
p.SetValue(oControl, propValue, Nothing)
End If
Next
End If
End Sub

call above code as:
to set value in lable:
SetControlPropertyValue(lablel1, "Text", "Hello")
To set value in progressbar:
SetControlPropertyValue(ProgressBar1, "value", i)


For SETTING FUNCTION VALUE for any control below code will help u out from error:
example for listbox:
Private Delegate Sub stringDelegate(ByVal s As String)
Private Sub AddItem(ByVal s As String)
If ListBox1.InvokeRequired Then
Dim sd As New stringDelegate(AddressOf AddItem)
Me.Invoke(sd, New Object() {s})
Else
ListBox1.Items.Add(s)
End If
End Sub

call above code by calling "AddItem()"

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates