Blank OP
Blank OP

Reputation: 9

Counting the number of highlighted words in richtextbox using c#

private void button2_Click(object sender, EventArgs e)
{ 
    string[] show = richTextBox1.Text.Split(' '); 
    string type = textBox1.Text; 
    for (int i = 0; i < show.Length; i++)
    {
        int num = 0; 
        if (show[i] == textBox1.Text)
            num++;
    } 
    Label1.Text = num.ToString();   
}

Im using richTextBox1 to display the file and the textBox1 to search for a word and highlight it. I want to display how many words are highlighted in the label box but it always shows zero. Any help is appreciated.

Upvotes: 0

Views: 131

Answers (2)

Ctznkane525
Ctznkane525

Reputation: 7465

You need to consider the new line character condition.

In my example, I remove Chr(13) and replace Chr(10) with a space, so it behaves the same way as a space character:

        string[] show = richTextBox1.Text.Replace(Convert.ToChar(13).ToString(), " ").Replace(Convert.ToChar(10).ToString(), " ").Split(' ');
        string type = textBox1.Text;
        int num = 0;
        for (int i = 0; i < show.Length; i++)
        {

            if (show[i].Trim() == textBox1.Text)
                num++;
        }
        textBox1.Text = num.ToString();

Upvotes: 0

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

You should move int num = 0; out of your loop, since in each iteration it will be set to 0;

Upvotes: 2

Related Questions