How to clear form fields in C #?

2

I'm doing a project for college, I created a GroupBox and inside it has RadioButton , Label , MaskedTexbox and TextBox . When I click the cancel button I cleaned MaskTexbox and TextBox and disabled Textbox . It just cleaned and had to repeat the code to clean it goes below.

private void toolStripButtonCancelar_Click(object sender, EventArgs e)
{
    rdbAprovadoAberto.Enabled = false;
    rdbReprovadoAberto.Enabled = false;
    lblNomeUser.Text = "Sistema";

    maskDataAprovReprov.Text = "";// limpa o campo MaskedTextBox
    txtMotivoReprovaAberto.Text = "";// limpa o campo TextBox
    this.txtMotivoReprovaAberto.Enabled = false;

    // tenho que duplicar o código senão não limpa os campos e desabilita txtMotivoReprovaAberto

    rdbAbertoAberto.Checked = true;
    maskDataAprovReprov.Text = "";
    txtMotivoReprovaAberto.Text = "";
    txtMotivoReprovaAberto.Enabled = false;
}

And this also worked out more I do not know if it's good practices

private void toolStripButtonCancelar_Click(object sender, EventArgs e)
{   
    rdbAprovadoAberto.Enabled = false;
    rdbReprovadoAberto.Enabled = false;
    lblNomeUser.Text = "Sistema";

    if (rdbAprovadoAberto.Checked)
    {
        maskDataAprovReprov.Text = "";
    }

    if (rdbReprovadoAberto.Checked)
    {
        maskDataAprovReprov.Text = "";
        txtMotivoReprovaAberto.Text = "";
        txtMotivoReprovaAberto.Enabled = false;
    }
}
    
asked by anonymous 18.01.2015 / 21:31

4 answers

2

I like to make a generic method. For example, in the following code I clear all text boxes from a FORM . You can put other conditions to check other types of components of FORM and do what you want.

foreach (Control c in this.Controls)
{
    if (c.GetType().ToString() == "System.Windows.Form.Textbox")
    {
        c.Text = "";
    }
}
    
20.06.2016 / 23:43
1

Break your code more, for easier reading. The smaller the code easier to understand and debug.

Then you can improve gradually. it is better to see duplicate code or code (in this case the functions) with more than one responsibility.

Many conditions in the same function may leave your code unreadable and difficult to maintain.

    
19.01.2015 / 02:01
1

Use TextBox1.Text = string.Empty;

If it's several do it like this:

 public void limpaCampos()
 {
   TextBox1.Text  = 
   TextBox2.Text  = 
   TextBox3.Text  = 
   TextBoxn.Text  = string.Empty;
 }
    
19.01.2015 / 18:37
1

I often create a clean-only method. There is how to do generic methods, for all controls, but I do one for each situation, it is of your preference.

Avoid using TextBox1.Text = ""; instead prefer to use: TextBox1.Text = string.Empty; As well as getting more elegant, avoid unintentionally pressing the spacebar between quotation marks and then mela all your code.

Create methods only for this, do not clear the click cancel button as you did, instead call the cleanup method only.

    
19.01.2015 / 11:59