简体   繁体   中英

C# - How to make pass a class as an parameter

So I wrote a code to check if there is any field empty in the my form.I have multiple forms and I have to use this validation check in several of them.I wanted to write it as a global function so I don't have to write the same lines of code again and again.But the code contains the reference to "this".How to take form class that is calling it as parameter so I can make the code global.Here is my code:

        // Checks if any field is empty.
        foreach (Control ctrl in this.Controls)
        {
            // Checking if it is a textbox.
            if (ctrl is TextBox)
            {
                TextBox txtbx = ctrl as TextBox;
                if (txtbx.Text == String.Empty)
                {
                    MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtbx.Focus();
                }
            }

            // Checking if it is a combobox.
            else if (ctrl is ComboBox)
            {
                ComboBox cmbbx = ctrl as ComboBox;
                if (cmbbx.Text == String.Empty)
                {
                    MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbbx.Focus();
                }
            }
        }

What changes is to be made to code so it can be used globally.For Example so that it can be called this way:

ValidateForm(this);

Or is there is better way to do it?

You can move that block of code into a separate method that accepts a Form :

public class Helper
{
    public static void Validate(Form form)
    {
        foreach (Control ctrl in form.Controls)
        {
            ...
            ...
        }
    }
}

You could also select all the empty controls at once using LINQ, then focus on the first one.

var invalidControls = form.Controls.Cast<Control>()
                          .Where(c => (c is TextBox || c is ComboBox) && c.Text == string.Empty);

if (invalidControls.Any())
{
    MessageBox.Show("Please fill all the fields", "Empty Fields",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);

    invalidControls.First().Focus();
}

You might want to look into indicating the invalid fields all at once, so the user doesn't potentially fix one, just to get the same message on each of the following ones, one at a time.

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