Search code examples
c#textboxtrim

How to trim unwanted letters from textbox continuously?


I am creating a project where the program fetches data from a serial port and displays it in a textbox. But along with the data, some unwanted characters are also getting inputted in the textbox through the serial port. I tried to trim them with '.Trim()' method by adding it in the textchanged event. But I could not get the desired outcome. I want the unwanted letters to get continuously trimmed from the textbox and the method should keep running in the background. Below is the code I tried out:

private void textBoxResults_TextChanged(...)
{
  char[] trim= ['a', 'b'];
  textBoxResults.Text.Trim(trim);
}

Please note that those are multiple letters(e.g. they could be g, m, a, etc.) I want all the unwanted ones to be trimmed from the textbox either directly when serialport data is received or after input from serial port.


Solution

  • Not exactly what all of you said, but something grouped after googling a bit.

    string ToBeReplaceCharacters = @"a;b";
    foreach(var RepChar in ToBeReplaceCharacters)
    {
      textBox1.Text = textBox1.Text.Replace(RepChar.ToString(), "");
    }
    

    What Stackloyd said is ok for single character but not multiple characters to be replaced. The above code fulfils my demand.

    Thank You All!