user2046417
user2046417

Reputation:

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 ?

Upvotes: 0

Views: 420

Answers (3)

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

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.

Upvotes: 2

Khan
Khan

Reputation: 18142

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
    }
}

Upvotes: 0

Jay
Jay

Reputation: 10108

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();} }

Upvotes: 0

Related Questions