0

我创建了一个新标签页,还向其中添加了一个富文本框:

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

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

因此,从外观上看,这似乎.Item()不是访问控件的正确方法。

那么如何访问动态创建的控件呢?

4

1 回答 1

2

您正在按名称将动态控件添加到容器中,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)
于 2011-06-13T19:44:38.477 回答