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()"
How to use controls in function used by Thread
Posted by
Rajesh Rolen
at
Tuesday, January 5, 2010
Labels: C#.NET and VB.NET Interview Questions , Threading , VB.NET
0 comments:
Post a Comment