Question : VB.NET: get control by name and Reflection performance

Hi X-perts,

To get a control by name I am using the following code (via Reflection). My questions:

1) Does it loop throughout all the controls to find a matching control?

2) If it is the case, how can I improve its performance in case of large forms with thousands of controls?

3) are there any other ways of getting a control by name or tag?

Thanks
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
Public Function GetControlByName(ByVal Name As String) As Control
 
            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

Answer : VB.NET: get control by name and Reflection performance

Here are some other solutions ...

        'using the GetControlByName function
        Me.GetControlByName(Name)

        'using the method find in the controls collection
        Me.Controls.Find(Name, True)

        'looping through all the controls and search for the name
        For Each ctr As Control In Me.Controls
            If ctr.Name = Name Then
                Return ctr
            End If
        Next
Random Solutions  
 
programming4us programming4us