0

So this is my code for the RESET button. it's pretty complex and long.

 textBox1.Text = string.Empty;
 comboBox1.Text = string.Empty;
 textBox2.Text = string.Empty;
 radioButton1.Checked = false;
 radioButton2.Checked = false;
 checkBox1.Checked = false;
 checkBox2.Checked = false;
 comboBox2.Text = string.Empty;
 textBox3.Text = string.Empty;
 textBox4.Text = string.Empty;
 textBox5.Text = string.Empty;

I Was Wondering can i just simplify this command using Looping or something?

Daniel
  • 7
  • 2

1 Answers1

1

Your example is definitely not complex. It is very straightforward; there is no question about what is going on in your code. And, in my opinion, it is not very long. I like it.

That being said, if you have a lot of code that empties out multiple textboxes, you could be write a little method like this one:

void ClearTextboxes(params TextBox[] args)
{
    foreach (var textbox in args) textbox.Text = string.Empty;
}

Then call it with

ClearTextboxes(textBox1, textBox2, textBox3, textBox4, textBox5);

Or if you plan to do this to every single textbox on the form, you could do something like this:

foreach (var textbox in this.Controls.OfType<TextBox>()) textbox.Text = string.Empty;

And you could do similar things for checkboxes and radio buttons, e.g.

foreach (var checkbox in this.Controls.OfType<CheckBox>()) checkbox.Checked = false;

P.S. If you really want to make your code easier to work with, I would rename those controls with names that are meaningful, e.g. instead of textBox1 perhaps UserNameTextBox (or some other descriptive name). That would be a much bigger improvement than shortening the clear command code.

John Wu
  • 50,556
  • 8
  • 44
  • 80