0

I have a tab control, which holds tab pages that have 1 text box in each of them. I have 2 buttons that change the selected tab page's text box to the text "Hello World."

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    CType(TabControl1.SelectedTab.Controls.Item(0), TextBox).Text = "Hello World."
End Sub

When I try to dim the text box control as text 1 at the top of the class,

Dim text1 As TextBox = CType(TabControl1.SelectedTab.Controls.Item(0), TextBox)

System.NullReferenceException was unhandled by user code
HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=HelloWorld StackTrace: at HelloWorld.frmMain..ctor() in E:\HelloWorld\HelloWorld\Form1.vb:line 6 InnerException:

I get this error because the tab page, with the text box is created when the form loads.

Dim tbTab = New TabPage()
Dim tbTextbox = New TextBox()

tbTab.Controls.Add(tbTextbox) 'Adds text box to new tab page
TabControl1.TabPages.Add(tbTab) 'Adds new tab page to tab control

So my question is how can I dim text1, publicity like you do on top of class

Dim text1 As TextBox = CType(tcTabs.SelectedTab.Controls.Item(0), TextBox)

after the tab page has been created, so I don't get errors. I want to be able to make the buttons do

text1.Text = "Hello World."

without having to dim text1 on each sub.

hey123
  • 5
  • 3
  • Simply declare the `text1` at the form level `Private text1 As TextBox` and assign `text1` a value in the the form's `Load` event handler, or wherever it is that you create the `TabControl` and the `TextBox`. – Blackwood Mar 03 '16 at 04:34
  • The TextBox and TabControl and TabPage do not exist yet where you are trying to reference and use them – Ňɏssa Pøngjǣrdenlarp Mar 03 '16 at 11:58

0 Answers0