프로그래밍언어/VB.NET

변수이름으로 컨트롤 접근

부산딸랑이 2014. 3. 19. 16:13

출처 : http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=45&MAEULNo=18&no=509&ref=509


Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim myControl As String = "Label"
        Dim i As Integer = 3
        FindByName(Of Label)(myControl + i.ToString()).Text = "test"


        '(myControl + i.ToString()).FindByName(Of Label)(Me).Text = "test"  'VB.NET은 이런 문법은 안됨. C#은 가능

        Dim controlName As String = myControl & i.ToString()
        controlName.FindByName(Of Label)(Me).Text = "test"

    End Sub
End Class


Public Module ControlSelectorExtension
    <System.Runtime.CompilerServices.Extension()>
    Public Function FindByName(Of T)(targetClass As Object, name As String) As T
        Dim info As Reflection.PropertyInfo = targetClass.GetType().GetProperty(name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
        Return DirectCast(info.GetValue(targetClass, Nothing), T)
    End Function

    <System.Runtime.CompilerServices.Extension()>
    Public Function FindByName(Of T)(name As String, targetClass As Object) As T
        Dim info As Reflection.PropertyInfo = targetClass.GetType().GetProperty(name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)

        Return DirectCast(info.GetValue(targetClass, Nothing), T)
    End Function

End Module