This is a really simplified version of your code. To create a method for reuse everywhere create a new Utility.cs file containing a simple static class
namespace MyApp.Utilities
{
public static class MyUtility
{
public static void PadForTextBox(TextBox tb)
{
if (tb.Text.Length < tb.MaxLength)
tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
}
}
}
Now you could call this method from every form that has a reference to the namespace where you define the class.
public void tb_Leave(object sender, EventArgs e)
{
Utility.PadForTextBox(sender as TextBox);
}
Another elegant method to achieve the same result is through an extension method for the TextBox
namespace MyApp.Utilities
{
public static class TextBoxExtensions
{
public static void PadForTextBox(this TextBox tb)
{
if (tb.Text.Length < tb.MaxLength)
tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
}
}
}
and call it with
public void tb_Leave(object sender, EventArgs e)
{
(sender as TextBox).PadForTextBox();
}
By the way, using these methods allow you to get rid also of that ugly sequence of casts.
Of course your tb_Leave method is an event handler and as that it should be linked to the textboxes.
If you want to have a textbox event handler common for every textboxes in you apps indipendently from the form in which the textboxes are created, then you cannot rely on the WinForm Designer, but you need to add manually the event handler to your textboxes in the form constructor just after the InitializeComponent call. All in all I prefer to leave this task to the designer and add the single line above when needed.
For example:
InitializeComponent();
// connect the leave event for 3 textboxes to the same static method inside the
// MyUtility static class
textBox1.Leave+=MyUtility.PadEventForTextBox;
textBox2.Leave+=MyUtility.PadEventForTextBox;
textBox3.Leave+=MyUtility.PadEventForTextBox;
.....
public static void PadEventForTextBox(object sender, EventArgs e)
{
TextBox tb=sender as TextBox;
if (tb.Text.Length<tb.MaxLength)
tb.Text=tb.Text.PadLeft(tb.MaxLength, '0');
}