I am creating a C# WinForms application in VS 2010. I have 10 TextBoxes.
For TextBox1
, I handled the events for GotFocus
, LostFocus
, etc. in the following manner:
this.richTextBox1.GotFocus += new System.EventHandler(this.RichTextBox1_GotFocus);
this.richTextBox1.LostFocus += new System.EventHandler(this.RichTextBox1_LostFocus);
private void TextBox1_GotFocus(object sender, System.EventArgs e)
{
TextBox1.BackColor = Color.White;
}
private void TextBox1_LostFocus(object sender, System.EventArgs e)
{
TextBox1.BackColor = Color.LightSteelBlue;
}
And now I need to write the same code for all of my textboxes. Is it instead possible to have a common GotFocus
, LostFocus
, etc. event handler method for all textboxes to do the above things?
You can create a custom textbox and use that in stead of copying the same handling call for each textbox. Please take a look at this link for similar idea.
If you really need this for 10 different textboxes, the best (and most object-oriented) thing to do would be to create your own custom textbox control that inherits from
System.Windows.Forms.TextBox
.Since you're inheriting from the base
TextBox
class, you get all of its functionality for free, and you can also implement the custom behavior that you want. Then just use this custom control as a drop-in replacement for the standard textbox control wherever you want controls with this behavior on your form. This way, you don't have to attach any event handlers at all! The behavior is built right into your control, following the guidelines of encapsulation and don't-repeat-yourself.Sample class:
Of course:
Just make "normal" methods GotFocus, LostFocus etc. and let the events of all text boxes call those methods.
EDIT:
Okay, here you are:
There is only one method for GotFocus, and only one method for LostFocus.
There are two text boxes, and the events of both call the same GotFocus and LostFocus method.
The GotFocus and LostFocus methods have a reference to who called them (the first parameter "sender", so they know which text box to change.