2010-11-24 29 views
1

我想問爲什麼我的代碼不起作用?C#查找函數問題(無法突出顯示)

目前,我能夠找到單詞用戶輸入,但它不能突出顯示richTextBoxConversation中的單詞。

我應該怎麼做呢?

以下是我的代碼:

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!"); 
     } 
    } 
+0

你需要用RichTextBox.Find()返回的值做些什麼嗎? – ddrace 2010-11-24 07:53:02

回答

0

您可以在RichTextBox中選擇文本,但是您需要始終記住,如果該richtextbox具有焦點,文本將處於選定模式,因此您的代碼必須是

// 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!"); 
} 
6

您正在使用Find方法 - 這只是告訴你其中這個詞存在文本框,它不會選擇它。

您可以依次用Select使用來自Find返回值 「亮點」 字:

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

,或者甚至更好(避免搜索s1兩次字):

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!"); 
} 
+0

我不知道爲什麼,但它仍然沒有突出顯示richtextbox中的單詞。無論如何,你能向我解釋爲什麼它的詞位> -1?爲什麼-1而不是其他數字? – athgap 2010-11-24 08:08:42

+0

@athgap - 如果您閱讀find(我鏈接了它)的文檔,它會告訴您,如果找不到**,則Find的返回值爲'-1'。 – Oded 2010-11-24 08:10:19