Category / Section
How to search and highlight string using Code snippets?
2 mins read
In EditControl, at present there is no default support to search and highlight required string and it can be achieved by using the SelectLines function and Lines collection in the EditControl.
SelectLines
This function helps to highlight the string.
Lines
This property will have the entire content of EditControl in the form of a collection.
The following Code sample demonstrates the same.
C#
/// <summary>
/// Event to search and highlight the string
/// </summary>
public void Button_Click(object sender, RoutedEventArgs e)
{
//Get the string we need to find
Edit1.FindOptions.FindText = txtbox.Text;
for(int i=next;i<=Edit1.Lines.Count;i++)
{
//Check whether Lines collection contains the required string
if (i<Edit1.Lines.Count && Edit1.Lines[i].Text.Contains(Edit1.FindOptions.FindText))
{
string pat = @"" + Edit1.FindOptions.FindText;
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(Edit1.Lines[i].Text);
//Get the string index and length
Edit1.SelectLines(i, i, m.Index, m.Index + m.Length);
next = i + 1;
break;
}
//Displays the MessageBox if the string is not present in the Lines collection
else if (i == Edit1.Lines.Count)
{
MessageBox.Show("Reached the end of the document.\nThe String is not found");
next = 0;
break;
}
}
}
VB
''' <summary>
''' Event to search and highlight the string
''' </summary>
Public Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
'Get the string we need to find
Edit1.FindOptions.FindText = txtbox.Text
For i As Integer = [next] To Edit1.Lines.Count
'Check whether Lines collection contains the required string
If i<Edit1.Lines.Count AndAlso Edit1.Lines(i).Text.Contains(Edit1.FindOptions.FindText) Then
Dim pat As String = "" & Edit1.FindOptions.FindText
Dim r As New Regex(pat, RegexOptions.IgnoreCase)
Dim m As Match = r.Match(Edit1.Lines(i).Text)
'Get the string index and length
Edit1.SelectLines(i, i, m.Index, m.Index + m.Length)
[next] = i + 1
Exit For
'Displays the MessageBox if the string is not present in the Lines collection
ElseIf i = Edit1.Lines.Count Then
MessageBox.Show("Reached the end of the document." & ControlChars.Lf & "The String is not found")
[next] = 0
Exit For
End If
Next i
End Sub
Screenshot
