Capture TextBox that called the event

3

I want to implement the wind GotFocus in a TextBox , so that when it gets focus, it sets the Text property to string.empty .

However, I have 6 TextBox that will execute this event. How do I identify which TextBox ? And how do I set the Text property to string.empty ?

    
asked by anonymous 09.05.2017 / 02:53

2 answers

5

Using the sender that is received per parameter in the event.

private void txtBox_GotFocus(object sender, EventArgs e)
{
    var txt = (TextBox)sender;
    txt.Text = "";
}
    
09.05.2017 / 14:05
2

In this answer a good explanation about sender was given.

For your case, completing the jbueno response, I've implemented a way to assign all textboxes to the GotFocus event. Also, a way to assign only to a certain group of controls.

The region I created can be converted to a method if you want.

public Form1() {
    InitializeComponent();

    #region Atribui a TODOS os textbox o evento GetFocus            
    //cria uma lista com todos os controles do formulário do tipo TextBox
    var listTextBox = this.Controls?.OfType<TextBox>();

    //Se por exemplo, você tiver um conjunto de textbox onde, só a eles deseja esse evento,
    //então poderá filtrar pelo nome deles - ou qualquer outra propriedade    
    var listTextBox = this.Controls?.OfType<TextBox>().Where(p => p.Name.Contains("TextBoxOpcoes"));

    foreach (var item in listTextBox) {
        item.Enter += new EventHandler(TextBoxOpcoes_GotFocus);
    }            
    #endregion
}

//Método que irá limpar a propriedade Text do controle
private void TextBoxOpcoes_GotFocus(object sender, EventArgs e) {
    ((TextBox)sender).Text = String.Empty;
}
    
09.05.2017 / 14:46