0

我有这个大项目,我期待着开展工作。会有很多带有很多文本框的表单,我不想在每个表单中编写代码。我想用方法创建一个类来验证这些文本框。我不知道怎么做。

我希望这些方法接受一个文本框,例如:ValidateTextBoxForInt(textbox1)并验证它。我将以这种方式使用它:

return ValidateTextBoxForInt(textbox1, textbox2);

(我可能只有 1 个文本框,可能有 100 个文本框……取决于需要验证 int 的文本框数量。)

任何人都可以向我推荐任何东西吗?帮我解决这个问题?

谢谢 :)

4

2 回答 2

1

You could have a custom form which inherits from a regular form. It will have some Validate event, which will trigger it to go through all contained TextBoxes, validate those and provide some help message to let user know about the errors.

When enumerating through TextBoxes, don't forget that Form.Controls is a tree, not a list, so you may need recursion or flatten this tree first, to account for TextBoxes inside panels, tab controls etc.

于 2013-05-22T20:46:29.073 回答
0

创建一个验证器类并调用它,传入一个控件,该控件是所有控件的父TextBox控件,例如 Panel:

public class Validator
{
    public bool ValidateAsInt(Control control)
    {
        bool valid = true;

        if (control.GetType() == typeof(TextBox))
        {
            int outVal = 0;
            if (0 == int.TryParse(((TextBox)control).Text, outVal))
            {
                valid = false;
            }
        }

        if (valid)
        {
            foreach (Control childControl in control.Controls)
            {
                if (!ValidateAsInt(childControl))
                {
                    valid = false;
                    break;
                }
            }
        }
        return valid;
    }
}
于 2013-05-22T21:53:34.180 回答