Select the contents of a TextBox by taking the focus

1

Is there any way that when the focus is positioned on each type control TextBox contained in a form, select the text contained in these?

I mean if there is any way to do this without having to program the ENTER event for each text box, since I have many.

It occurs to me that with a foreach but I do not see in which event to insert the code.

EDIT:

Between the solution provided by the friend NaCI and some tweaks that I did to make it work as expected, the code was like this:

private void RecorrerControles(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c.HasChildren) this.RecorrerControles(c);
            {
                foreach (TextBox t in c.Controls.OfType<TextBox>())
                {
                    t.Enter += delegate
                    {
                        t.SelectAll();
                        t.HideSelection = false;
                    };
                    t.Leave += delegate
                    {
                        t.SelectionLength = 0;
                    };
                } 
            }
        }
    }

I defined it as a private method to access it only from this form, which I call from the constructor of the form.

In the first instance it did not work for me because I have the form organized in panels and the solution that happened to me NaCI only ran through the TextBox contained directly in the form and not in the panels. For this, I defined a function that calls itself if the control has "children" and runs through the contained controls, until there are no more "children".

    
asked by Willy616 20.04.2017 в 19:35
source

1 answer

1

You can see the edition history for my previous answer.

This solution works perfectly as you expect:

// Recuerda el using System.Linq;
// y el using System.Windows.Forms;
// Form1 es tu formulario
public Form1() 
{
    foreach (TextBox t in this.Controls.OfType<TextBox>()) 
    {
        t.Enter += delegate { 
            t.SelectAll(); 
            t.HideSelection = false; 
        };
        t.Leave += delegate { 
            t.SelectionLength = 0; 
            t.HideSelection = true; 
        };
    } 
}

The HideSelection property is responsible for hiding the control selection when taking the focus, the code if you have selected the text, but it is not reflected in the form, but you can still perform actions with the selection.

    
answered by 20.04.2017 / 19:53
source