[c#] Auto highlight text in a textbox control

How do you auto highlight text in a textbox control when the control gains focus.

This question is related to c# textbox

The answer is


In Windows Forms and WPF:

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

I think the easiest way is using TextBox.SelectAll like in an Enter event:

private void TextBox_Enter(object sender, EventArgs e)
{
    ((TextBox)sender).SelectAll();
}

If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:

this.textBox1.Click += new System.EventHandler(textBox1_Click);

in:

partial class Form1
{
    private void InitializeComponent()
    {

    }
}

where textBox1 is the name of the relevant textbox located in Form1

And then create the method definition:

void textBox1_Click(object sender, System.EventArgs e)
{
    textBox1.SelectAll();
}

in:

public partial class Form1 : Form
{

}

if you want to select all on "On_Enter Event" this won't Help you achieving your goal. Try using "On_Click Event"

    private void textBox_Click(object sender, EventArgs e)
    {
        textBox.Focus();
        textBox.SelectAll();
    }

It is very easy to achieve with built in method SelectAll

Simply cou can write this:

txtTextBox.Focus();
txtTextBox.SelectAll();

And everything in textBox will be selected :)


Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.

public class AutoSelectAll
{
    public static bool GetIsEnabled(DependencyObject obj) 
    { 
        return (bool)obj.GetValue(IsEnabledProperty); 
    } 
    public static void SetIsEnabled(DependencyObject obj, bool value) 
    { 
        obj.SetValue(IsEnabledProperty, value);
    }

    static void ue_Loaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        ue.GotFocus += ue_GotFocus;
        ue.GotMouseCapture += ue_GotMouseCapture;
    }

    private static void ue_Unloaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        //ue.Unloaded -= ue_Unloaded;
        ue.GotFocus -= ue_GotFocus;
        ue.GotMouseCapture -= ue_GotMouseCapture;
    }

    static void ue_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    static void ue_GotMouseCapture(object sender, MouseEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
        typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));

    static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ue = d as FrameworkElement;
        if (ue == null)
            return;
        if ((bool)e.NewValue)
        {
            ue.Unloaded += ue_Unloaded;
            ue.Loaded += ue_Loaded;
        }
    }
} 

The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.

You can use this by including the following tag in your xaml.

<TextBox  
    Text="{Binding Property}"
    Library:AutoSelectAll.IsEnabled="True" />

If you want to do it for your whole WPF application you can do the following: - In the file App.xaml.cs

    protected override void OnStartup(StartupEventArgs e)
    {
        //works for tab into textbox
        EventManager.RegisterClassHandler(typeof(TextBox),
            TextBox.GotFocusEvent,
            new RoutedEventHandler(TextBox_GotFocus));
        //works for click textbox
        EventManager.RegisterClassHandler(typeof(Window),
            Window.GotMouseCaptureEvent,
            new RoutedEventHandler(Window_MouseCapture));

        base.OnStartup(e);
    }
    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        (sender as TextBox).SelectAll();
    }

    private void Window_MouseCapture(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
             textBox.SelectAll(); 
    }

If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.

Just handling the FocusEnter event doesn't work, because the Click event comes afterwards, and overrides the selection if you SelectAll() in the Focus event.

private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
    isFirstTimeEntering = true;
}

private void textBox_Click(object sender, EventArgs e)
{
    switch (isFirstTimeEntering)
    {
        case true:
            isFirstTimeEntering = false;
            break;
        case false:
            return;
    }

    textBox.SelectAll();
    textBox.SelectionStart = 0;
    textBox.SelectionLength = textBox.Text.Length;
}

I don't know why nobody mentioned that but you can also do this, it works for me

textbox.Select(0, textbox.Text.Length)

In window form c#. If you use Enter event it will not work. try to use MouseUp event

    bool FlagEntered;
    private void textBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if ((sender as TextBox).SelectedText == "" && !FlagEntered)
        {
            (sender as TextBox).SelectAll();
            FlagEntered = true;
        }
    }

    private void textBox1_Leave(object sender, EventArgs e)
    {
        FlagEntered = false;
    }

In ASP.NET:

textbox.Attributes.Add("onfocus","this.select();");

On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0

public static class TbHelper
{
    // Method for use
    public static void SelectAllTextOnEnter(TextBox Tb)
    {
        Tb.Enter += new EventHandler(Tb_Enter);
        Tb.Click += new EventHandler(Tb_Click);
    }

    private static TextBox LastTb;

    private static void Tb_Enter(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        Tb.SelectAll();
        LastTb = Tb;
    }

    private static void Tb_Click(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        if (LastTb == Tb)
        {
            Tb.SelectAll();
            LastTb = null;
        }
    }
}

If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.


textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

You can use this, pithy. :D

TextBox1.Focus();    
TextBox1.Select(0, TextBox1.Text.Length);

 textBoxX1.Focus();
 this.ActiveControl = textBoxX1;
 textBoxX1.SelectAll();