Inserting text into a TextBox

Filed in WPFTags: ,

Recently I wanted to add a newline character to a text box when the user pressed Shift+Enter. The TextBox control in WPF already has a built in AppendText method, however it doesn’t have a built in InsertText method. So I decided to create an extension to add this functionality.

In order to insert text into the text box, I called the Insert method on the text box’s Text property. The text was inserted, but the side affect was that the caret position was moved to the beginning of the text box. So I just moved it back. This is a pretty simple piece of code, so I don’t know why it isn’t included. Here’s the code.


using System.Windows.Controls;

namespace MyCo.MyApp.Extensions
    public static class TextBoxExtensions
        public static void InsertText(this TextBox element, int index, string textToInsert)
            element.Text = element.Text.Insert(index, textToInsert);
            element.CaretIndex = index + 1;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

WordPress database error Table '27178_beckerswebsite.wp_formbuilder_pages' doesn't exist for query SELECT * FROM wp_formbuilder_pages made by require('E:\inetpub\vhosts\\httpdocs\wp-blog-header.php'), require_once('E:\inetpub\vhosts\\httpdocs\wp-includes\template-loader.php'), do_action('template_redirect'), call_user_func_array, formbuilder_init, fb_is_active