Reputation: 111
I am trying to highlight multiple lines of specific text in a RichTextBox.
Here is my code for highlighting text:
public void HighlightMistakes(RichTextBox richTextBox)
{
string[] phrases = { "Drivers Do Not Match", "Current Does Not Match", "No Drivers Found" };
foreach (var phrase in phrases)
{
int startIndex = 0;
while (startIndex <= richTextBox.TextLength)
{
int phraseStartIndex = richTextBox.Find(phrase, startIndex, RichTextBoxFinds.None);
if (phraseStartIndex != -1)
{
richTextBox.SelectionStart = phraseStartIndex;
richTextBox.SelectionLength = phrase.Length;
richTextBox.SelectionBackColor = Color.Yellow;
}
else break;
startIndex += phraseStartIndex + phrase.Length;
}
}
}
Here is how I add text to RTB and call function above:
foreach (var a in resultList)
{
richTextBox1.AppendText("\n"+a + "\n");
HighlightMistakes(richTextBox1);
}
However, HighlightMistakes
doesn't work the way I would like it to. The idea is to highlight all string values specified in phrases
array and that doesn't happen every time.
Examples:
I am not sure why some of the lines are skipped and some of them are not.
Upvotes: 1
Views: 1200
Reputation: 32288
If you have nothing against a simple Regex method, you can use Regex.Matches to match your list of phrases against the text of your RichTextBox.
Each Match in the collection of Matches contains both the Index (the position inside the text) where the match is found and its Length, so you can simply call .Select(Index, Length) to select a phrase and highlight it.
The pattern used is the string resulting from joining the phrases to match with a Pipe (|
).
Each phrase is passed to Regex.Escape(), since the text may contain metacharacters.
If you want to considere the case, remove RegexOptions.IgnoreCase
.
using System.Text.RegularExpressions;
string[] phrases = { "Drivers Do Not Match",
"Current Does Not Match",
"No Drivers Found" };
HighlightMistakes(richTextBox1, phrases);
private void HighlightMistakes(RichTextBox rtb, string[] phrases)
{
ClearMistakes(rtb);
string pattern = string.Join("|", phrases.Select(phr => Regex.Escape(phr)));
var matches = Regex.Matches(rtb.Text, pattern, RegexOptions.IgnoreCase);
foreach (Match m in matches) {
rtb.Select(m.Index, m.Length);
rtb.SelectionBackColor = Color.Yellow;
}
}
private void ClearMistakes(RichTextBox rtb)
{
int selStart = rtb.SelectionStart;
rtb.SelectAll();
rtb.SelectionBackColor = rtb.BackColor;
rtb.SelectionStart = selStart;
rtb.SelectionLength = 0;
}
Upvotes: 1