Re: object reference error
Try the following
Code:
Private Sub demo()
Dim activeRichTextBox As New RichTextBox
If TypeOf Me.ActiveControl Is RichTextBox Then
activeRichTextBox = DirectCast(Me.ActiveControl, RichTextBox)
If activeRichTextBox.Text.Length > 0 Then
' assumes SpellChecker exists already and has been properly created
SpellChecker.Text = activeRichTextBox.Text
SpellChecker.SpellCheck()
Else
MsgBox("Text box is empty")
End If
Else
Console.Write("Nope")
End If
End Sub
Re: object reference error
Doesn't the menuitem become the activecontrol when you click on it? And obviously a menuitem cannot be cast to a richtextbox, so TryCast(me.activecontrol, richtextbox) returns Nothing therefore you get a null reference exception when you try to treat Nothing as a richtextbox.
Re: object reference error
So would it be better if I had a right click menu on the RTB?
Re: object reference error
Possibly not... as then the menu would become the active control.
the way I'd deal with it (and admittedly it is far less than ideal) is to create a form level object of type RTB... then as an RTB gets focus (I'm assuming you have more than one) ... set the form-level object equal to the RTB that just got focus... then use the form-level object in your code above.
-tg
Re: object reference error
Quote:
Originally Posted by
stanav
Doesn't the menuitem become the activecontrol when you click on it? And obviously a menuitem cannot be cast to a richtextbox, so TryCast(me.activecontrol, richtextbox) returns Nothing therefore you get a null reference exception when you try to treat Nothing as a richtextbox.
Yes the menu item becomes the active control but the ContextMenu SourceControl property indicates which control invoked the menu item as shown below.
Code:
Private Sub DemoToolStripMenuItem_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles DemoToolStripMenuItem.Click
If ContextMenuStrip1.SourceControl IsNot Nothing Then
If TypeOf ContextMenuStrip1.SourceControl Is RichTextBox Then
Dim activeRichTextBox As New RichTextBox
activeRichTextBox = DirectCast(ContextMenuStrip1.SourceControl, RichTextBox)
activeRichTextBox.AppendText("Hello")
End If
End If
End Sub
Re: object reference error
Thanks techgnome, I will give that a shot
And thank Kevin, I will look over that as well.