2011-06-13 42 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