views:

390

answers:

4

For example I only the second character in each line to be an x, while the 3nd to 10th character must be a hex digit. At the moment I use a Select Case, then check the position of the caret (using textbox.selectionstart) and see if the key being pressed is a "legal" character.

Is there a better way of doing this as it slows down on large amounts of text.

This is the code I have at the moment:

 Select Case TextBox1.SelectionStart
     Case TextBox1.GetFirstCharIndexOfCurrentLine + 1 
         If Not e.KeyChar = "x" Then
             e.Handled = True
         End If
     Case (TextBox1.GetFirstCharIndexOfCurrentLine + 2) To (TextBox1.GetFirstCharIndexOfCurrentLine + 9) 
         Dim allowedchars As String = "abcdefABCDEF0123456789" & vbCrLf & Chr(Keys.Back)
         If allowedchars.Contains(e.KeyChar) Then
             e.Handled = False
         Else
             e.Handled = True
         End If
 End Select
+1  A: 

You could just allow entering anything, and then check the validity of the entire string using a single regex. That will speed up things quite a bit, especially on large amounts of text.

RegDwight
Also, going by the caret position makes it hard to deal with pasted text. Definitely better to check the whole thing with a regexp after the user has done.
vincebowdren
A: 

I'm not sure about the performance difference, but something like this might be faster to test your 1st and 3rd-9th characters (I apologize if my VB is a little off, it's been awhile):

If Not Char.IsControl(e.KeyChar) Then    
    Dim test As Int = 0
    Integer.TryParse(e.KeyChar.ToString(), System.Globalization.NumberStyles.HexNumber, Nothing, ByRef test)
    If test = 0 Then
        e.Handled = True
    End If
End if

Edit -- Forgot the Control Char test...

Jacob G
A: 

Can you just stop checking after the 10th character?

 If TextBox1.SelectionStart < 11 Then
   ' your code
 End If
Jeff O
A: 

You say it slows down on large amounts of text; maybe it's the TextBox1.GetFirstCharIndexOfCurrentLine call that takes longer with large amounts of text. You call it three times, but you could only call it once:

Dim firstChar As Integer = TextBox1.GetFirstCharIndexOfCurrentLine()

Select Case TextBox1.SelectionStart
    Case firstChar + 1 
        ...
    Case firstChar + 2 To firstChar + 9
        ...
 End Select

Code looks cleaner too!

Meta-Knight