开发者

C# find function problem (Can't highlight)

I would like to ask why does my codes not work?

Currently, I am able to find the word the user input but it cannot highlight the word in the richTextBoxConversation.

How should I go about doing it?

Following are my codes:

    private void buttonTextFilter_Click(object sender, EventArgs e)开发者_运维问答
    {
        string s1 = richTextBoxConversation.Text.ToLower();
        string s2 = textBoxTextFilter.Text.ToLower();

        if (s1.Contains(s2))
        {
            MessageBox.Show("Word found!");
            richTextBoxConversation.Find(s2);
        }
        else
        {
            MessageBox.Show("Word not found!");
        }
    }


You are using the Find method - this simply tells you where in the textbox the word exists, it does not select it.

You can use the return value from Find with Select in order to "highlight" the word:

if (s1.Contains(s2))
{
  MessageBox.Show("Word found!");
  int wordPosition = richTextBoxConversation.Find(s2); // Get position
  richTextBoxConversation.Select(wordPosition, s2.Length);
}

Or, even better (avoids searching s1 twice for the word):

int wordPosition = richTextBoxConversation.Find(s2); // Get position
if (wordPosition > -1)
{
  MessageBox.Show("Word found!");
  richTextBoxConversation.Select(wordPosition, s2.Length);
}
else
{
  MessageBox.Show("Word not found!");
}


You can select text in RichTextBox but you need to always remember that text will be in selected mode if that richtextbox has focus, so your code must be

// RichTextBox.Select(startPos,length)

int startPos = richTextBoxConversation.Find(s2); 

int length = s2.Length;

if (startPos > -1)
{
    MessageBox.Show("Word found!");
    // Now set focus on richTextBox
    richTextBoxConversation.Focus();
    richTextBoxConversation.Select(startPos , length );
}
else
{
    MessageBox.Show("Word not found!");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜