I'm new in Vb.net and try to make a simple program. I need one variable to be used in all subs. How can i do that with this:
RTB As Richtextbox = CType(TabControl1.SelectedTab.Controls.Item(0), Richtextbox)
I'm new in Vb.net and try to make a simple program. I need one variable to be used in all subs. How can i do that with this:
RTB As Richtextbox = CType(TabControl1.SelectedTab.Controls.Item(0), Richtextbox)
was on the right track wanting a single RichTextBox reference for use in multiple subs, and 's pointer to search is fine, but the runtime error happens because the control reference is Nothing when the field is initialized. Initializing a form-level variable from another control at declaration time runs before the designer-created controls exist, so attempting to cast a missing object raises the NullReferenceException (see the .NET docs on NullReferenceException).
A reliable pattern is to declare the variable at class scope but assign it after InitializeComponent has run (for example in Form.Load) or to compute the current RichTextBox on demand. Example: declare the field, then find and store the RichTextBox in Load and update it on tab changes.
Private RTB As RichTextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RTB = Nothing
If TabControl1.SelectedTab IsNot Nothing Then
For Each c As Control In TabControl1.SelectedTab.Controls
If TypeOf c Is RichTextBox Then
RTB = CType(c, RichTextBox)
Exit For
End If
Next
End If
End Sub An alternative that avoids keeping a possibly stale reference is a read-only property that returns the RichTextBox found in the currently selected tab each time it is needed:
Private ReadOnly Property CurrentRTB As RichTextBox
Get
If TabControl1.SelectedTab Is Nothing Then Return Nothing
For Each c As Control In TabControl1.SelectedTab.Controls
If TypeOf c Is RichTextBox Then Return CType(c, RichTextBox)
Next
Return Nothing
End Get
End Property Practical tips: use TryCast when appropriate to avoid exceptions, always check for Nothing before using the reference, and refresh the stored reference in the TabControl.SelectedIndexChanged handler if tabs can change. See the Microsoft documentation on NullReferenceException and the TryCast operator for details.
Search in google, you will definitly get information.
Search in google, you will definitly get information.
I use this,
Public RTB As Richtextbox = CType(TabControl1.SelectedTab.Controls.Item(0), Richtextbox)
Private Sub (Blah Blah) Handles Button1.Click
If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
RTB.Font = FontDialog1.Font
End If
End Sub
And Get error: Object reference not set to an instance of an object.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.