Applying code to a control written at runtime

x2i

Member
Joined
Jan 26, 2007
Messages
5
Programming Experience
1-3
I recently used a custom class to allow me to make rich text boxes that integrate syntax highlighting. However, when i try to refer to this textbox in the code - it threw an error claiming the control didnt exist (understandable seeing as it is written as the program runs) and would not compile.

Can this be resolved :confused:
 
When you generate control dynamically you either
1) add it to a Controls collection where it can be rediscovered by searching it
VB.NET:
    Sub createcontrols1()
        Dim tb As New TextBox
        tb.Name = "tbid"
        Me.Controls.Add(tb)
    End Sub
 
    Sub usecontrols1()
        Dim tb As TextBox = Me.Controls.Find("tbid", False)(0)
        tb.Text = "gotcha1"
    End Sub
2) or keep the reference at higher scope level and use that reference.
VB.NET:
    Private tb As TextBox
 
    Sub createcontrols2()
        tb = New TextBox
    End Sub
 
    Sub usecontrols2()
        tb.Text = "gotcha2"
    End Sub

EDIT:
I just noticed your profile is .Net 1.1. Controls.Find method is new in .Net 2.0. You can use this Find function instead:
VB.NET:
    Private Function find(ByVal key As String) As Control
        For Each c As Control In Me.Controls
            If c.Name = key Then Return c
        Next
        Return Nothing
    End Function
 
Last edited:
Back
Top