2012-08-07 14 views
11

Nel mio RichtextBox, se ho scritto come di seguito.Evidenzia tutta la parola cercata in richtextbox

Questa è la mia penna,
la sua penna è bella.

Ora la parola di ricerca "è" quindi l'output sarebbe come indicato di seguito.

Tutti "è" devono essere evidenziati.

saluti, Khilen

+2

Anche la "è" presente in "questo" e la "sua" dovrebbe essere evidenziato? – digEmAll

risposta

16

Che dire:

static class Utility { 
    public static void HighlightText(this RichTextBox myRtb, string word, Color color) { 

     if (word == string.Empty) 
      return; 

     int s_start = myRtb.SelectionStart, startIndex = 0, index; 

     while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) { 
      myRtb.Select(index, word.Length); 
      myRtb.SelectionColor = color; 

      startIndex = index + word.Length; 
     } 

     myRtb.SelectionStart = s_start; 
     myRtb.SelectionLength = 0; 
     myRtb.SelectionColor = Color.Black; 
    } 
} 
+1

Perché stai cercando due volte la singola parola dalla posizione startIndex con: 'while (myRtb.Text.IndexOf (word, startIndex)! = -1) { int index = myRtb.Text.IndexOf (word, startIndex); '? Penso che dovresti salvare l'indice trovato nel ciclo while. –

0

si presenta così l'avrebbe fatto.

http://www.dotnetcurry.com/ShowArticle.aspx?ID=146

int start = 0; 
int indexOfSearchText = 0; 

    private void btnFind_Click(object sender, EventArgs e) 
    { 
     int startindex = 0; 

     if(txtSearch.Text.Length > 0) 
      startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length); 

     // If string was found in the RichTextBox, highlight it 
     if (startindex >= 0) 
     { 
      // Set the highlight color as red 
      rtb.SelectionColor = Color.Red; 
      // Find the end index. End Index = number of characters in textbox 
      int endindex = txtSearch.Text.Length; 
      // Highlight the search string 
      rtb.Select(startindex, endindex); 
      // mark the start position after the position of 
      // last search string 
      start = startindex + endindex; 
     } 
    } 

    public int FindMyText(string txtToSearch, int searchStart, int searchEnd) 
    { 
     // Unselect the previously searched string 
     if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0) 
     { 
      rtb.Undo(); 
     } 

     // Set the return value to -1 by default. 
     int retVal = -1; 

     // A valid starting index should be specified. 
     // if indexOfSearchText = -1, the end of search 
     if (searchStart >= 0 && indexOfSearchText >=0) 
     { 
      // A valid ending index 
      if (searchEnd > searchStart || searchEnd == -1) 
      { 
       // Find the position of search string in RichTextBox 
       indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None); 
       // Determine whether the text was found in richTextBox1. 
       if (indexOfSearchText != -1) 
       { 
        // Return the index to the specified search text. 
        retVal = indexOfSearchText; 
       } 
      } 
     } 
     return retVal; 
    } 

// Reset the richtextbox when user changes the search string 
    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     start = 0; 
     indexOfSearchText = 0; 
    } 
+0

Questo troverà solo la prima occorrenza, voglio evidenziare tutta la parola che corrisponde a –

0

questo mostrerà tutti i criteri ricercate allo stesso tempo.

Utilizzo: 1 Casella di testo (per immettere il testo da cercare) e 1 pulsante (per eseguire la ricerca).

Immettere i criteri di ricerca all'interno della casella di testo e premere il pulsante di ricerca.

 // On Search Button Click: RichTextBox ("rtb") will display all the words inside the document 
    private void btn_Search_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      if (rtb.Text != string.Empty) 
      {// if the ritchtextbox is not empty; highlight the search criteria 
       int index = 0; 
       String temp = rtb.Text; 
       rtb.Text = ""; 
       rtb.Text = temp; 
       while (index < rtb.Text.LastIndexOf(txt_Search.Text)) 
       { 
        rtb.Find(txt_Search.Text, index, rtb.TextLength, RichTextBoxFinds.None); 
        rtb.SelectionBackColor = Color.Yellow; 
        index = rtb.Text.IndexOf(txt_Search.Text, index) + 1; 
        rtb.Select(); 
       } 
      } 
     } 

     catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } 
    } 
} 

}

3

Utilizzando questo metodo, sarà in grado di evidenziare più parole, allo stesso tempo. Oppure puoi saltare facilmente la parte foreach e usarla per evidenziare una singola parola.

private void HighlightWords(string[] words) 
{ 
    foreach (string word in words) 
    { 
     int startIndex = 0; 
     while (startIndex < rich.TextLength) 
     { 

      int wordStartIndex = rich.Find(word, startIndex, RichTextBoxFinds.None); 
      if (wordStartIndex != -1) 
      { 
       rich.SelectionStart = wordStartIndex; 
       rich.SelectionLength = word.Length; 
       rich.SelectionBackColor = Color.Yellow; 
      } 
      else 
       break; 
      startIndex += wordStartIndex + word.Length; 
     } 
    } 
} 
0

Sono d'accordo con la soluzione di Alex Jolig in alto. Ma ho trovato una cosa, l'ultima riga,

startIndex + = wordStartIndex + word.Length;

non dovrebbe avere + =, invece,

startIndex = wordStartIndex + word.Length;

Questo funzionerà.

0

Se si desidera abbinare l'intera parola che si può usare, si noti che questo ignora il caso e anche i | s \ b significa che i plurali vengono evidenziati per es. Cat corrisponde gatti ma non Caterpiller:

public static void HighlightText(RichTextBox myRtb, string word, Color color) 
    { 
     if (word == string.Empty) 
      return; 
     var reg = new Regex(@"\b" + word + @"(\b|s\b)",RegexOptions.IgnoreCase); 

     foreach (Match match in reg.Matches(myRtb.Text)) 
     { 
      myRtb.Select(match.Index, match.Length); 
      myRtb.SelectionColor = color; 
     } 

     myRtb.SelectionLength = 0; 
     myRtb.SelectionColor = Color.Black; 
    } 
0
private void button3_Click(object sender, EventArgs e) 
    { 
     if (textBox1.Text != "") 
     { 
      for (int i = 0; i < richTextBox1.TextLength; i++) 
      { 
       richTextBox1.Find(textBox1.Text, i, RichTextBoxFinds.None); 
       richTextBox1.SelectionBackColor = Color.Red; 
      } 
     } 
     else 
     { 
      for (int i = 0; i < richTextBox1.TextLength; i++) 
      { 
       richTextBox1.SelectAll(); 
       richTextBox1.SelectionBackColor = Color.White; 
      } 
     } 
    }[lets make it!][1] 
+0

Spiega la tua risposta invece di fornire semplicemente il codice. Inoltre, mentre la soluzione sembra funzionare, questa domanda è piuttosto vecchia e ha già una risposta accettata. Il tuo aiuto sarebbe molto più apprezzato sulle nuove domande :) –

+0

OK sicuro. Thankful –

+0

Puoi trovare molte informazioni su come funziona questo sito nel Centro assistenza, ad esempio: Come rispondere: http://stackoverflow.com/help/how-to-answer –

Problemi correlati