PDA

View Full Version : Selection.Start returns error when creating a new line..


JoshMiles
Nov 13, 2012, 01:00 PM
Hey,
I'm really stuck and stumped on how to go about fixing this problem.
Essentially, the user enters some text into a RichTextBox(Named Content) and whilst the user is typing, it runs a if loop to see if it matches a word, and if it does, it highlights it.
Here is the code for the Content_TextChanged:


Private Sub Content_TextChanged(sender As Object, e As EventArgs) Handles Content.TextChanged

Dim words() As String = Content.Text.Split(" ")

For Each word As String In words
If (word.StartsWith("#")) Then

HighLight(word, Color.LightGreen)

ElseIf (word.StartsWith("<")) Then

HighLight(word, Color.Aquamarine)

ElseIf (word = "{" Or word = "}" Or word.StartsWith("{") Or word.StartsWith("}") Or word.EndsWith("{") Or word.EndsWith("}")) Then


End If
Next

End Sub

As you can see, it asks for the sub HighLight:


Public Sub HighLight(ByVal word As String, ByVal color As Color)
If (word = "") Then
Else

Content.SelectionStart = Content.Find(word)
Content.SelectionColor = color

Content.SelectionStart = Content.TextLength
Content.SelectionLength = 0
Content.SelectionColor = color.White
End If

End Sub

The error is thrown when you press Enter on the richtextbox after you have just entered something that has had it's colour changed... if you understand me.
E.G: The user enters "#include" which is changed to the colour Light Green when typing, then the user enters '<stdio.h>' which is changed to Aqua Marine.
So the user has currently only entered: "#include <stdio.h>"
The trouble is when the user hits enter to create a new line, it throws this error:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll

Additional information: InvalidArgument=Value of '-1' is not valid for 'SelectionStart'.

The problem doesn't occur when the user hits space before going onto a new line.
Any help?

Regards,
Josh

GaryStaunton
Nov 14, 2012, 06:01 PM
Obviously you need to handle the error.

Content.SelectionStart = Content.Find(word)


Try assigning the .Find function to a variable and check it first:

lngWordPos = Content.Find(word)

If lngWordPos < 0 Then
'// Do not bother processing, exit the routine
End If

Hope that helps
G