Apply event format to all textboxes

Viewed 69

I have written this code:

private void maskedNASC_KeyDown(object sender, KeyEventArgs e)
{  
    maskedNASC.BackColor = Color.Aqua;
}

private void maskedNASC_Leave(object sender, EventArgs e)
{  
    maskedNASC.BackColor = Color.White;
}

I want to apply this property to all the textboxes and masked texts of the form.

I have see many codes like this:

void SetProperty(Control ctr) // resalta textbox onfocus
{
    foreach (Control control in ctr.Controls)
    {
        if (control is TextBox)
        {
            control.Leave == control.BackColor = Color.Aqua;
            control.KeyDown += BackColor = Color.White ;
        }
    }
}

What is the right way to write this??

Thanks. Alejandro.

I have add this to the form1.designer :

this.maskedNASC.Leave += TextBoxEvent_Leave;
this.maskedNASC.KeyDown += TextBox_KeyDown;

but the code below have an error

 [![enter image description here][1]][1]
2 Answers

You can write that in this way

void SetProperty(Control ctr) // resalta textbox onfocus
{
    foreach (Control control in ctr.Controls)
    {
        if (control is TextBox)
        {
            control.Leave -= control_Leave; //Remove control_Leave if already binded. 
            control.Leave += control_Leave; //Assigne control_Leave 
            control.KeyDown -= control_KeyDown ; //Remove control_KeyDown if already binded. 
            control.KeyDown += control_KeyDown ; //Assigne control_KeyDown 
        }
    }
}



private void control_Leave(object sender, EventArgs e)
{
   ((Control)sender).BackColor = Color.Aqua;
}

private void control_KeyDown(object sender, KeyEventArgs e)
{
   ((Control)sender).BackColor = Color.White;
}

You can make the event more general for example (using pattern matching in C# 8.0)

    private void TextBoxEvent_Leave(object sender, EventArgs e)
    {
        if (sender is TextBox bx)
        {
            bx.BackColor = Color.White;
        }
    }

    private void TextBox_KeyDown(object sender, EventArgs e)
    {
        if (sender is TextBox bx)
        {
            bx.BackColor = Color.Red;
        }
    }

and in the constructor just add

        this.maskedNASC.Leave += TextBoxEvent_Leave;
        this.maskedNASC.KeyDown += TextBox_KeyDown;

for each text box you have

you can also try the following depending on the C# version you are using

    private void TextBoxEvent_Leave(object sender, EventArgs e)
    {
        if (sender is TextBox)
        {
            ((TextBox)sender).BackColor = Color.White;
        }
    }

    private void TextBox_KeyDown(object sender, EventArgs e)
    {
        if (sender is TextBox)
        {
            ((TextBox)sender).BackColor = Color.Red;
        }
    }
Related