Question

I have a form with some fields on it:

folderNameLabel
folderTitle
folderDescription
folderCategory

Before the user will press OK, I want to check if all that fields are not =="". I wanted to make a function to receive an array as parameter and return a bool value, but I am not sure how to write it...

Was it helpful?

Solution

You could do the following:

private void btnOK_Click(object sender, EventArgs e)
{
    bool fieldsFilled = ValidateStrings(folderNameLabel.Text, 
                                        folderTitle.Text, 
                                        folderDescription.Text, 
                                        folderCategory.Text);
    if (fieldsFilled)
        DialogResult = DialogResult.OK;
    else
    {
        // Report errors
    }
}

private bool ValidateStrings(params string[] items)
{
    bool result = true;
    for (int i = 0; i < items.Length && result; i++)
        result &= !String.IsNullOrWhitespace(items[i]);

    return result;
}

Question: How do you tell the user which field he missed?

In your case, you could show a "You need to fill in all fields" message, but having only one optional field, that doesn't work anymore. This is why usually you don't do something like above.

OTHER TIPS

public bool Validate(List<string> parameters)
{
   foreach(string parameter in parameters)
   {
        if(String.IsNullOrEmpty(parameter))
        {
            return false;
        }
   }
   return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top