Clearing Multiple TextBoxes in C#

  • Thread starter Thread starter bernden
  • Start date Start date
B

bernden

Good Morning

I am working on a C# project that has a form which contains multiple
columns of 10 textBoxes in seperate groupBoxes on a tabControl.
When the form loads, I would like to make sure that text property of each
individual textBox is set to "0.00" .
When the form closes, I would like to ensure that the text property of ALL
textboxes is re-set to "null" or " " .

Is there a way to do this without having to list each textBox and set its
text property individually ?

Any help / insight would be appreciated.

Dennis
 
Good Morning Tim

Thank you for that quick and timely reply.
I tried it out and it worked like a charm. In fact it worked so well that I
adjusted it to suit the needs of specific events
within my little program and they did the job perfectly.
Here is an example of those adjustments. Perhaps another C# novice like
myself can benefit from your assistance as I did.

sample
private void cboxS1_Checked(object sender, System.EventArgs e)
{
foreach(Control ctrl in this.gboxStdS1.Controls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = "0.00" ;
}

Thanks again
Dennis
 
A more encapsulated approach is to make the textbox itself responsible
for setting and resetting its values - by inheriting and changing the
TextBox behaviour.

First create a new type of Control:

/// <summary>
/// CustomTextBox takes responsibility for
/// initialising and resetting itself.
/// </summary>
public class CustomTextBox : System.Windows.Forms.TextBox
{
private void SetToNull(object sender, EventArgs eventArgs)
{
Text = string.Empty;
}

protected override void OnCreateControl()
{
base.OnCreateControl();
Text = "0.00";
Form form = FindForm();
form.Closed += new EventHandler(SetToNull);
}
}

Then change the codebehind of the form to use the custom textbox:

private void InitializeComponent()
{
...
this.textBox1 = new CustomTextBox();
...
}

That way there's no risk of you changing other text boxes by mistake.

rob styles
 
Back
Top