简体   繁体   中英

How to re-use the same code for clearing text boxes

I have so many text boxes and about five buttons. I want to clear the text boxes and do some other things which are repeating in all five buttons. I want to create a new class and put all the code which is repeating so that I can re-use the code through a function or method. But, the problem is if I create a new class, the text boxes are recognized. For example, If I say txtFirstName.Clear() in a new class, it is not recognized as it is a new class. Is there any way around ?

Create a Utility class with static methods for the code you need to re-use all the time. An example would be a method that you could pass a container reference to it and it would clear all the textboxes (Or Make them read only) inside that container or any child containers. See code below :

public class utility
{

public static void MyTextBoxes(Control container, string CommandName){

        foreach (Control c in container.Controls){
        MyTextBoxes(c, CommandName);        

        if(c is TextBox){ 
          switch (CommandName)
          {
            case "Clear":
                c.Text = "";   
                break;
            case "ReadOnly":
                ((TextBox)c).ReadOnly = true;
                break;
          }  

        }   
    }    
}

In your Form code, call the method like this :

utility.MyTextBoxes(this, "Clear");
utility.MyTextBoxes(this, "ReadOnly");

This way I used the same method to perform different commands by specifying the command as string. You could have different methods do different commands (for code readability) if you wish. I'm sure this has given you an idea on how to create utility methods.

You can pass the textbox reference to a new method on your class.

public void ClearTextbox(Textbox textBoxToClear) { textBoxToClear.Clear; }

just pass your textbox to the new method.

or to clear a bunch of textboxes:

public void ClearTextBoxes(IEnumerable<Textbox> textBoxesToClear) { foreach(Textbox textbox in textBoxesToClear) {textbox.Clear();} }

You can achieve this by passing your current form in as a parameter to the constructor of the new class.

public class MyNewClass
{
    Form1 _form;

    public MyNewClass(Form1 form)
    {
        _form = form;
    }

    public void ClearTextBoxes()
    {
        _form.txtFirstName.Clear();
        //Clear the rest
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM