-2

I have two TextBox controls

  • one for searching
  • one for the text it self

If I click the Search button I want the search word in the text box to be highlighted.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
  • 1
    Adding some code would help solve your problem faster. – MrHunter Apr 08 '14 at 13:26
  • Plenty of example here... http://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp - they are c# but an online converter will help – Mych Apr 08 '14 at 13:56

1 Answers1

1

Assuming you are building a desktop application.

If you simply want to highlight the first word in the text content that matches the search word, you can use String.IndexOf to find the word. Then you can highlight using the returned index:

For example in WPF you could add a click event handler to the search button:

Private Sub SearchButton_Click(sender As Object, e As RoutedEventArgs)
    ' Find index of first match
    Dim index = ContentBox.Text.IndexOf(SearchBox.Text)
    ' Check for match
    If index = -1 Then Return
    ' Set focus
    ContentBox.Focus()
    ' Select first matching word
    ContentBox.SelectionStart = index
    ContentBox.SelectionLength = SearchBox.Text.Length
End Sub

If you want to highlight all words in the text content that match the search word, you will need to call String.IndexOf multiple times using the overload that takes the start index for the search. To show multiple words highlighted you will need to use a RichTextBox available in both WPF and WinForms.

Phillip Trelford
  • 6,513
  • 25
  • 40