@sharon glipman , based on my test, I find that I can run your code to color the specific word in the Richtextbox.
Also, Please note that you missing some code here, I make some changes on it.
Change this
for (int ix = 0; ;)
into:
for (int ix = 0;ix<s.Length ;ix++)
Here is a code example that works for me.(Only Changed the above code)
List<int> results = new List<int>();
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
richTextBox1.Text = File.ReadAllText(listView1.Items[listView1.SelectedIndices[0]].Text);
FileInfo fi = new FileInfo(listView1.Items[listView1.SelectedIndices[0]].Text);
//lblfilesizeselected.Text = ExtensionMethods.ToFileSize(fi.Length);
//lblfilesizeselected.Visible = true;
string filePath = Path.GetDirectoryName(fi.FullName);
string word = textBox1.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];
}
}
}
}
void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0;ix<s.Length ;ix++)
{
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;
}
private void Form1_Load(object sender, EventArgs e)
{
listView1.SelectedIndexChanged += listView1_SelectedIndexChanged;
listView1.View = View.Details;
listView1.Columns.Add("Path");
listView1.Columns.Add("Name");
ListViewItem lvi = new ListViewItem();
lvi.Text = "D:\\1.txt";
lvi.SubItems.Add("test1");
ListViewItem lvi1 = new ListViewItem();
lvi1.Text = "D:\\2.txt";
lvi1.SubItems.Add("test2");
ListViewItem lvi2 = new ListViewItem();
lvi2.Text = "D:\\3.txt";
lvi2.SubItems.Add("test3");
listView1.Items.Add(lvi);
listView1.Items.Add(lvi1);
listView1.Items.Add(lvi2);
}
Result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.