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.
CodePudding user response:
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;
}
CodePudding user response:
You can make the event more general for example
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