locked
Insert text at cursor position in RTB RRS feed

  • Question

  • I need some sample code on inserting text at the current cursor position in Rich Text Box in a windows application.  
    Friday, January 9, 2009 10:25 AM

Answers

  • OK. Inserting text at the caret position and replacing selected text are two diferent things. To replace the selected text you will need to remove the text that is selected before inserting your text at the selectionstart position:

                if (richTextBox1.SelectionType == RichTextBoxSelectionTypes.Text || richTextBox1.SelectionType == RichTextBoxSelectionTypes.MultiChar|| )
                    richTextBox1.Text = ricgTextBox1.Text.Remove(richTextBox1.SelectionStart, richTextBox1.SelectionLength).Insert( richTextBox1.SelectionStart, "This is my text");
    Ole - Andre Johansen | Hire Me !
    • Marked as answer by Sagar K S Tuesday, January 13, 2009 4:35 AM
    Monday, January 12, 2009 3:15 PM

All replies

  •             if (richTextBox1.SelectionType == RichTextBoxSelectionTypes.Empty)
                    richTextBox1.Text = richTextBox1.Text.Insert(richTextBox1.SelectionStart, "this is my text");

    Ole - Andre Johansen | Hire Me !
    Friday, January 9, 2009 11:52 AM
  • Hi, thanks for your reply. but the RTB is not getting updated with the new inserted string. kindly help.
    Monday, January 12, 2009 4:34 AM
  • The code works. What seems to be the problem? Please explain a bit more precise.
    Ole - Andre Johansen | Hire Me !
    Monday, January 12, 2009 8:45 AM
  • Appreciate your quick response. my requirement is to change the selected text as i explained below,

    If the RTB contains - This is sample text.
    I select the word sample and on click event of a button, the text of the RTB should be changed as - This is <sample> text.

    Monday, January 12, 2009 9:03 AM
  • OK. Inserting text at the caret position and replacing selected text are two diferent things. To replace the selected text you will need to remove the text that is selected before inserting your text at the selectionstart position:

                if (richTextBox1.SelectionType == RichTextBoxSelectionTypes.Text || richTextBox1.SelectionType == RichTextBoxSelectionTypes.MultiChar|| )
                    richTextBox1.Text = ricgTextBox1.Text.Remove(richTextBox1.SelectionStart, richTextBox1.SelectionLength).Insert( richTextBox1.SelectionStart, "This is my text");
    Ole - Andre Johansen | Hire Me !
    • Marked as answer by Sagar K S Tuesday, January 13, 2009 4:35 AM
    Monday, January 12, 2009 3:15 PM
  • Appreciate your response. The given code is working :-).
    Tuesday, January 13, 2009 4:35 AM