I have a question. Can i select a string from my RichTextBox ?

For example:

I have this text:

English
Francais
Spaniol

And i want to select Francais , but as string , not at int - lenght ... ( richTextBox1.Select(7,15); )

I want something like:

richTextBox1.SelectString("Francais") , is there something like this ?

Dani AI

Generated

Yes — you can select text by value instead of hard-coding offsets. @ICode's IndexOf+Select approach is fine, but WinForms RichTextBox already provides a built-in search method and a couple of safer alternatives that handle case, whole-word, and repeated searches more cleanly.

A simple built-in option is RichTextBox.Find; it searches and sets the selection for you and returns the zero-based index (or -1 if not found):

int pos = richTextBox1.Find("Francais");
if (pos >= 0)
{
    // Find sets the selection; make it visible
    richTextBox1.ScrollToCaret();
}

See the API for overloads and flags that let you control options like case/whole-word matching: RichTextBox.Find

For pattern or whole-word matching you can use regular expressions and then set the selection using SelectionStart/SelectionLength (this avoids repeatedly scanning the text manually):

var m = System.Text.RegularExpressions.Regex.Match(
    richTextBox1.Text, @"\bFrancais\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (m.Success)
{
    richTextBox1.SelectionStart = m.Index;
    richTextBox1.SelectionLength = m.Length;
    richTextBox1.ScrollToCaret();
}

Reference: Regex.Match

Quick tips: use the RichTextBoxFinds overloads when you want case or whole-word handling without regex; use StringComparison (e.g., StringComparison.OrdinalIgnoreCase) if you fall back to IndexOf; store and restore the user's selection if you don't want to disrupt it; and be aware of CR/LF differences in indices when mixing RTF and plain-text processing.

I've used richtextbox a little bit, and well u can use richtextbox1.Select(7,12) (or whatever), but sometimes you wouldn't know where it ism so u could search the whole text thats in the richtextbox for the word your looking for,,,,and i wrote "Francais".Length, just incase its a variable, not a constant word...if it is u can use that or u can count it ur self ^^...lol

if (richTextBox1.Text.Contains("Francais"))
{
         int index=richTextBox1.Text.IndexOf("Francais");
         richTextBox1.Select(index, "Francais".Length);
         string retrieve_text = richTextBox1.SelectedText;
}

there might be another way...there might not,,,,,,but this should work

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.