Capture Textbox that called the event

Asked

Viewed 96 times

3

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

However, I have 6 TextBox that will run this event. How do I identify which TextBox? And how I define ownership Textas string.empty?

3 answers

6


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

private void txtBox_GotFocus(object sender, EventArgs e)
{
    var txt = (TextBox)sender;
    txt.Text = "";
}

2

In this reply was given a good explanation on the sender.

For your case, completing the jbueno answer, I implemented a way for you to assign to all textboxes the event GotFocus.
Including, a way to assign only to a certain group of controls.

The region that I created can be converted into 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;
}

0

A more elegant way would be!

    private void DataGridViewRegistrosCell_TextChanged_Exemplo(object sender, EventArgs e)
    {
            var cellValue = (sender as TextBox).Text;
            Debug.WriteLine($"O valor da célula é: {cellValue}");
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.