37

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

Ghasem
  • 14,455
  • 21
  • 138
  • 171
Kevin
  • 3,574
  • 10
  • 38
  • 43

16 Answers16

57

In Windows Forms and WPF:

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    What If you want to select multiple words, but not the words in-between? – f1wade Oct 15 '13 at 11:24
  • 1
    @f1wade Windows Forms TextBox does not support that. – Reed Copsey Oct 15 '13 at 17:07
  • 1
    UDP: tetxbox..SelectAll() is supported in WPF for Windows Phone 8 (not tested in other project types) – Epsil0neR Jan 16 '14 at 21:34
  • I found using the above code in the textbox's GotMouseCapture event to work just like I needed. – CMarsden Oct 03 '15 at 00:36
  • If the component inherits from TextBox like MakedTextBox, this maybe not work. If It is your case see this answer [Select all in MaskedTextBox](https://stackoverflow.com/questions/42818701/how-to-highlight-the-control-when-it-gets-focus/57242076#57242076) – fsbflavio Jul 28 '19 at 15:09
11

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(); 
    }
MontrealKid
  • 111
  • 1
  • 2
  • 2
    Worked for tabbing into a TextBox. Did not work so good for clicking in one. If you click on the text it quickly gets highlighted and then un-highlighted before showing up as you would expect with the cursor at the clicked location. – denver Feb 17 '15 at 21:27
10

In ASP.NET:

textbox.Attributes.Add("onfocus","this.select();");
beon
  • 493
  • 1
  • 4
  • 12
6

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 :)

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • Except that it doesn't. In my case I'm trying to select all text on enter event but instead nothing is selected and the caret stays pulsing. The event is fired as the breakpoint is hit. Any idea? – kuklei Nov 11 '20 at 12:17
  • Make sure that the HideSelection property of the text box is false, or you won't see the selection highlighted, which can be disconcerting. – S. Rojak Jun 24 '22 at 20:02
5

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
{

}
Jan
  • 141
  • 2
  • 7
2

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();
}
ShooShoSha
  • 956
  • 10
  • 17
  • Have you tried this? I copied your example and it does not select anything. – kuklei Nov 11 '20 at 12:18
  • I did over 5 years ago. It's also a snippet missing a lot of other code to wire the event to the control. But the method SelectAll is part of the TextBoxBase class: – ShooShoSha Nov 12 '20 at 19:25
  • 1
    Looks like the OnEnter event does not play nicely with the SelectAll() method. The OnEnter event of the textbox clears the selection from SelectAll(). – kuklei Nov 13 '20 at 11:32
  • Curious. It's hard to recall what my thinking was in the long ago, but I think I referred to the remarks of the Enter event and probably didn't notice the OnEnter method . Regardless, my example is lacking. – ShooShoSha Nov 19 '20 at 17:23
  • It has never worked. Click -> SelectAll works – Nick Turner May 10 '23 at 17:07
2

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" />
Zamotic
  • 1,127
  • 8
  • 12
1

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.

user260578
  • 11
  • 1
1

You can use this, pithy. :D

TextBox1.Focus();    
TextBox1.Select(0, TextBox1.Text.Length);
Majid
  • 101
  • 2
  • 11
1

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;
}
Brendan Gooden
  • 1,460
  • 2
  • 21
  • 40
1

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();
    }
Sayed Muhammad Idrees
  • 1,245
  • 15
  • 25
0

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;
        }
    }
}
Alatey
  • 371
  • 2
  • 6
0

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

textbox.Select(0, textbox.Text.Length)
believe me
  • 910
  • 1
  • 5
  • 24
0
 textBoxX1.Focus();
 this.ActiveControl = textBoxX1;
 textBoxX1.SelectAll();
0

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;
    }
congchien
  • 31
  • 1
-1
textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
Billy Moukas
  • 47
  • 1
  • 12
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this https://stackoverflow.com/help/how-to-answer – S.R Jun 18 '17 at 08:42