I have a list of items in a listView control name lvnf.
When I select an item in the listView it's reading the item file on the hard disk and show it's content in a richTextBox1.
After adding the file content to the richTextBox1 I want to highlight specific words in the richTextBox1 but coloring this words in yellow.
The problem is that it's coloring all the content in the richTextBox1.
myword in the foreach loop is each word(string) I want to color in yellow in the richTextBox1 but it's coloring all the content in richTextBox1 in yellow.
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (listViewCostumControl1.lvnf.SelectedItems.Count > 0)
{
results = new List<int>();
richTextBox1.Text = File.ReadAllText(listViewCostumControl1.lvnf.Items[listViewCostumControl1.lvnf.SelectedIndices[0]].Text);
FileInfo fi = new FileInfo(listViewCostumControl1.lvnf.Items[listViewCostumControl1.lvnf.SelectedIndices[0]].Text);
lblfilesizeselected.Text = ExtensionMethods.ToFileSize(fi.Length);
lblfilesizeselected.Visible = true;
filePath = Path.GetDirectoryName(fi.FullName);
string word = textBoxSearchBox.Text;
string[] test = word.Split(new string[] { ",," }, StringSplitOptions.None);
foreach (string myword in test)
{
HighlightPhrase(richTextBox1, myword, Color.Yellow);
lblviewerselectedfile.Text = results.Count.ToString();
lblviewerselectedfile.Visible = true;
if (results.Count > 0)
{
numericUpDown1.Maximum = results.Count;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value];
}
}
}
}
This method is the HighlightPhrase that should find the word/s in the richTextBox1
void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ;)
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0)
{
break;
}
else
{
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
results.Add(jx);
}
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
