Insert text in caret position programmatically

Good day.

I'm trying to insert text from code-behind in SfRichTextBoxAdv.
I read this KB article - https://www.syncfusion.com/kb/6306/how-to-modify-the-content-in-sfrichtextboxadv-programmatically, but still have questions.

How can I get caret position? Should I create Document and Section, if I just need to insert value of variable in caret position?
I would be really grateful for some working example.


2 Replies

VM Venkatesan Mani Syncfusion Team January 8, 2018 12:10 PM UTC

  
Hi Konstantin,

Thank you for contacting Syncfusion support.

The SfRichTextBoxAdv Selection API’s allows you to insert the text at current cursor(caret) position.  

To insert the text at current cursor position: 
Using the InsertText(string text) API of the SfRichTextboxAdv Selection instance you can insert your text at the current cursor position. 
The sample code from below table demonstrate how to insert the text at cursor position programmatically, 
XAML: 
<Grid> 
    <Grid.RowDefinitions> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 
    <StackPanel Orientation="Horizontal"> 
        <Button Margin="1" Content="Insert Text" Click="InsertText_Click"></Button> 
    </StackPanel> 
    <Border BorderThickness="1" BorderBrush="Black" Grid.Row="1"> 
        <Syncfusion:SfRichTextBoxAdv x:Name="richTextBoxAdv" Background="#F1F1F1" AcceptsTab="True"/> 
    </Border> 
</Grid> 

C#: 
private void InsertText_Click(object sender, RoutedEventArgs e) 
{ 
    if (richTextBoxAdv != null && richTextBoxAdv.Document != null) 
    { 
        // Inserts the text at current selection. 
        // If the selection is not empty (i.e., contains contents), then selected contents will be removed and the text will be inserted. 
        richTextBoxAdv.Selection.InsertText("Hello World!!!"); 
    } 
} 


Regards,
Venkatesan M. 



HG Hafthor Gudnason January 11, 2019 03:58 PM UTC

richTextBoxAdv.Selection.InsertText this throws errors when the text contains newline \n in version  16.4.0.42

Loader.
Up arrow icon