Question

How can I delete words from a "string" in the RichTextBox.

Example:

[02/04/2014 17:04:21] Thread 1 Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 2: Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 3: Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 4: Banned: xxxxxxxxx@xxxx.tld 

I would like to delete all rows with the word "Banned" in the line.

How can I do this?

Thanks in advance.

Was it helpful?

Solution

You can use LINQ to remove all the lines that contains the work "Banned":

richTextBox1.Lines = richTextBox1.Lines
    .Where((line, b) => !line.Contains("Banned"))
    .Select((line, b) => line).ToArray();

OTHER TIPS

I know this method looks ugly. But, if you don't want to remove formatting from the existing text in the richtextbox then you should use this method. This example is not tested but, you can get logic from here.

for (int iLine = 0; iLine < rtf.Lines.Length; iLine++)
{
    if (rtf.Lines[iLine].Contains("Banned"))
    {
        int iIndex = rtf.Text.IndexOf(rtf.Lines[iLine]);
        rtf.SelectionStart = iIndex;
        rtf.SelectionLength = rtf.Lines[iLine].Length;
        rtf.SelectedText = string.Empty;
        iLine--; //-- is beacause you are removing a line from the Lines array. 
    }
}

You could try use the answer from this post - I would adjust the code slightly to neaten it up a bit.

URL: what is the best way to remove words from richtextbox?

Code snippet from the URL (which would need to be tidied up).

string[] lines = richTextBox1.Lines;
List<string> linesToAdd = new List<string>();
string filterString = "Banned".";
foreach (string s in lines)
{
    string temp = s;
    if (s.Contains(filterString))
       temp = s.Replace(filterString, string.Empty);
    linesToAdd.Add(temp);
 }
 richTextBox1.Lines = linesToAdd.ToArray(); 

I would adjust the above code and whilst still using the loop, just check if the line contains the word you looking for "Banned" and then remove the line / do what is need with it.

I hope this helps?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top