Perform action in all textboxes without having to repeat for each one (C#)

Asked

Viewed 53 times

1

Well, I have a Windows Form program with 35 textboxes,and I want to perform the following action on all of them,:

    private void txtGSabado5_TextChanged(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(txtGSabado5.Text))
        {
            txtGSabado5.BackColor = Color.Red;
        }
        else
        {
            txtGSabado5.BackColor = Color.White;
        }

That is, if the textbox is empty it changes the background color to red.

1 answer

4


Welcome to the community!

You can go through each control of the Form through property Controls. So for each item, you define a Eventhandler that will execute the logic you want:

public MyForm()
{
    InitializeComponent();

    foreach(Control control in Controls)
    {
        if (control is TextBox)
        {
            control.TextChanged += Control_TextChanged;
        }
    }
}

private void Control_TextChanged(object sender, EventArgs e)
{
    // Como o parâmetros sender é do tipo object,
    // precisamos fazer um cast para o tipo de objeto do TextBox
    // Então, poderemos definir as propriedades dele
    TextBox textBox = (TextBox) sender;
    
    if (string.IsNullOrEmpty(textBox.Text))
    {
        textBox.BackColor = Color.Red;
    }
    else
    {
        textBox.BackColor = Color.White;
    }
}

Browser other questions tagged

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