What's Here?
- Members: 149,621
- Replies: 506,751
- Topics: 79,851
- Snippets: 2,666
- Tutorials: 706
- Total Online: 1,908
- Members: 65
- Guests: 1,843
|
This is a snippet I use to find specified text in a RichTextBox. I use it as a part of a Find And Replace system
|
Submitted By: PsychoCoder
|
|
|
Rating:
|
|
Views: 1,162 |
Language: C#
|
|
Last Modified: August 31, 2008 |
|
Instructions: Pass the text you're looking for, whether to match case or not and the RichTextBox you're looking in. |
Snippet
/// <summary>
/// method for searching for specified text in a RichTextBox
/// </summary>
/// <param name="text">text we're looking for</param>
/// <param name="matchCase">match case or not?</param>
/// <param name="rtb">RichTextBox we're searching for</param>
public static void Find(string text, bool matchCase, System.Windows.Forms.RichTextBox rtb)
{
try
{
//variable to hold the start position (start of the found text)
int startPos;
//what kind of search are we doing
StringComparison type;
//determine if it's a match case search or not
type = matchCase == true ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
//look for the search text
startPos = rtb.Text.IndexOf(text, type);
//check the position
if (!(startPos > 0))
{
//text doesn't exist so let the user know
MessageBox.Show("Search text: '" + text + "' could not be found", "Text Not Found", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
else
{
//Yureka! Select the found text
rtb.Select(startPos, text.Length);
//scroll to the found text
rtb.ScrollToCaret();
//add focus so the highlighting shows up
rtb.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Search Error");
}
}
Copy & Paste
|
|
|
Be Social
Reference Sheets
Bye Bye Ads
Monthly Drawing
Top Contributors
Top 10 Kudos This Month
|