Reputation: 45
I'm trying to highlight a particular line in my RichTextBox as shown in figure.
int ptrsize = 10;
int* linenum;
for (int i = 0; i < ptrsize; i++)
{
int value = (linenum[i]) * 10;
string searchText = value.ToString();
int indexToText = richTextBox.Find(searchText);
int endIndex = searchText.Length;
richTextBox.Select(indexToText, endIndex);
richTextBox.SelectionColor = Color.Blue;
}
If a text is present (i.e. 2010), i want to highlight the entire line.
2010 19.5 7.37 105 0.67 0.26 0.69
Upvotes: 0
Views: 2768
Reputation: 45
I made some changes in previous code with the help of @TaW's code.
for (int j = 0; j < ptrsize; j++)
{
int value = (linenum[j]) * 10;
string searchText = value.ToString();
for (int i = 0; i < richTextBox.Lines.Count(); i++)
{
highlightLineContaining(richTextBox, i, searchText, Color.Red);
}
}
Upvotes: 1
Reputation: 54453
This will highlight a given line if it contains a given text:
void highlightLineContaining(RichTextBox rtb, int line, string search, Color color)
{
int c0 = rtb.GetFirstCharIndexFromLine(line);
int c1 = rtb.GetFirstCharIndexFromLine(line+1);
if (c1 < 0) c1 = rtb.Text.Length;
rtb.SelectionStart = c0;
rtb.SelectionLength = c1 - c0;
if (rtb.SelectedText.Contains(search))
rtb.SelectionColor = color;
rtb.SelectionLength = 0;
}
You may want to store and restore the original Selection
.
Sometimes changing the SelectionBackColor
looks better. Give it a try!
You could call it on the whole RTB :
for (int i = 0; i < richTextBox.Lines.Count(); i++)
highlightLineContaining(richTextBox, i, searchText, Color.Red);
Upvotes: 3