How do I access a control on a form by name i.e. something on the lines of:
frmMain.Controls("btn1").Text = "Hello"
where the name will be dynamic e.g. "btn" & CStr(intCount).
The Controls method requires an integer index, how do I do the lookup?
Printable View
How do I access a control on a form by name i.e. something on the lines of:
frmMain.Controls("btn1").Text = "Hello"
where the name will be dynamic e.g. "btn" & CStr(intCount).
The Controls method requires an integer index, how do I do the lookup?
Found this code, it works but I don't know if it the best way of doing it:
http://www.planetsourcecode.com/URLS...10/anyname.htm
VB Code:
Public Function GetControlByName(ByVal Name As String) As Control 'now, why would I put a "_" in front of the name? Dim info As System.Reflection.FieldInfo = Me.GetType().GetField("_" & Name, _ System.Reflection.BindingFlags.NonPublic Or _ System.Reflection.BindingFlags.Instance Or _ System.Reflection.BindingFlags.Public Or _ System.Reflection.BindingFlags.IgnoreCase) If info Is Nothing Then Return Nothing Dim o As Object = info.GetValue(Me) Return o End Function
I can now say:
VB Code:
frmMain.GetControlByName("btn"+Cstr(intCount)).Text = "Hello"
Hi,
One way is to use an array of controls, e.g.
Dim arrControls(,) As Control
You can then add controls to the array at runtime and refer to them by their array index number
You could also use Reflection.
You might also be able to use the function CallByName(). It is supposed to be able to refer to Properties but I have only used it to refer to methods.
See if you can understand MSDN Help on this point :D
I had a look at CallByName before but the first arg seems to be a fixed object, which obviously I need to generate in code.
Hi,
The first argument in CallByName is the container. i.e. the form (Me) or a panel or groupbox.
Hi,
I've never tried it but I suppose you could put the CallByName code in a separate sub in the module and then call it, passing a parameter.
EG the following works for calling a method
[Highlight=VB]
In a frm1 event
ccc(frm1, "Test")
Public Sub ccc(ByVal str1 As Object, ByVal str2 As String)
Dim str3 As String = "Test"
CallByName(str1, str2, CallType.Method)
End Sub
Public Sub Test()
MessageBox.Show("It Works")
End Sub
[Highlight=VB]