2011-06-13 37 views
0

我创建了一个新的标签页,并还增加了一个RichTextBox到它在VB .NET控件:查找动态添加

Private Sub AddTab(ByVal ctrl As TabControl, _ 
           ByVal text As String) 
    If Me.InvokeRequired Then 
     Me.Invoke(New AddTabDelegate(AddressOf AddTab), _ 
        New Object() {ctrl, text}) 
     Return 
    End If 

    Dim NewTab As New TabPage 
    NewTab.Name = "OutputTab" & outputs.Item(outputs.Count - 1) 
    NewTab.Text = "Domain" 
    Dim NewTextbox As New RichTextBox 
    NewTextbox.Name = "OutputTextbox" & outputs.Item(outputs.Count - 1) 

    ctrl.Controls.Add(NewTab) 
    NewTab.Controls.Add(NewTextbox) 
End Sub 

现在我尝试别的地方访问RichTextBox的代码:

Dim NewTextbox As RichTextBox 
NewTextbox = Me.Controls.Item("OutputTextbox" & current_output) 
debug.print(NewTextbox.name) 

我得到以下错误:

A first chance exception of type 'System.NullReferenceException' occurred in program.exe 

我知道这个名字是分辩,因为我已经在创建方法打印的名字并且我在代码中打印了名称字符串,我尝试访问它。

因此,通过它的外观看起来.Item()不是访问控制的正确途径。

那么如何来访问动态创建的控制?

回答

1

你的名字ctrl添加动态控制到一个容器,后来在形式容器寻找它。您可以搜索使用递归,但Me.FindControl()你的情况,因为你知道,有RichTextBox的容器,这将是更有效地做一些事情,如下图所示。

尝试

Dim NewTextbox As RichTextBox 
Dim NewTab as TabPage 
NewTab = ctrl.Controls.Item("OutputTab" & current_output) 
NewTextbox = newTab.Controls.Item("OutputTextbox" & current_output) 

debug.print(NewTextbox.name) 
+0

感谢。我认为这是默认递归。 – PeeHaa 2011-06-13 20:06:09