Remove end character in a textbox without rewriting all the data

Lagg Master picture Lagg Master · Jul 3, 2012 · Viewed 7.4k times · Source

I am writing a program to communicate over the serial port. All data that is sent is mirrored back. Everything works fine except backspaces. When I hit the backspace button the only way I know how to remove the last character in the text box is to use a mid function then overwrite the current data with the new data. When a lot of data is inside the richtextbox it starts to flicker. I have tried using the richtextbox.text.remove function but I get this error. "Index and count must refer to a location within the string. Parameter name: count"

RichTextBox1.Text.Remove(RichTextBox1.TextLength, 1)

I have tried to throw some number into the function that does not cause it to error out but no data is removed from the richtextbox.

Here is the code that transmits data

   KeyCharString = e.KeyChar 'stores key being pressed into KeyCharString
    Try
        SerialPort1.Write(KeyCharString) 'tx data for key being pressed
    Catch ex As Exception
        MsgBox(ex.Message) 'Displays error if serialport1 cannot be written to
    End Try

    If Asc(KeyCharString) = 8 Then 'If char is a backspace remove precious character and exit sub
        RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.TextLength, 1)
        'RichTextBox1.Text = Mid(RichTextBox1.Text, 1, RichTextBox1.TextLength - 1)'Old code used to remove the character.  Causes the richtextbox to flicker when rewriting the data
        Exit Sub
    End If

This is the code that receives data

    receivedString = SerialPort1.ReadExisting.ToString

    If Asc(receivedString) = 8 Then 'deletes the received data if it is a backspace
        receivedString = ""
        Exit Sub
    End If
    RichTextBox1.AppendText(receivedString) 'adds new data to the richtextbox

Is there a way to remove 1 character from the richtextbox without rewriting all the data inside it? Also, the richtextbox is read only.

Answer

Mark Hall picture Mark Hall · Jul 4, 2012

The String.Remove method that you are using returns a String it does not do anything with the original string.

from MSDN Link:

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.

Try this but I am not sure of the flicker:

RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.TextLength - 1, 1)

or something like this:

RichTextBox1.SelectionStart = RichTextBox1.TextLength - 1
RichTextBox1.SelectionLength = 1
RichTextBox1.ReadOnly = False
RichTextBox1.SelectedText = ""
RichTextBox1.ReadOnly = True