C#Winforms文本框验证检查

C#Winforms文本框验证检查,c#,winforms,C#,Winforms,我在windows窗体中有3对文本框:- TxtboxSourceFolder1 -> TxtboxDestinationFolder1 TxtboxSourceFolder2 -> TxtboxDestinationFolder2 TxtboxSourceFolder3 -> TxtboxDestinationFolder3 我正在创建一个列表SrcFolders和一个列表DestFolders 现在我必须验证用户输入:- 1) TxtboxSourceFolder1是否有

我在windows窗体中有3对文本框:-

TxtboxSourceFolder1 -> TxtboxDestinationFolder1
TxtboxSourceFolder2 -> TxtboxDestinationFolder2
TxtboxSourceFolder3 -> TxtboxDestinationFolder3
我正在创建一个
列表SrcFolders
和一个
列表DestFolders

现在我必须验证用户输入:-

1) TxtboxSourceFolder1是否有值,如果有,TxtboxDestinationFolder1中是否有相应的值?如果所有答案都是“是”,并且值是合法的,则将它们添加到相应的列表中。然后重复

在我看来,检查文本框是否为空:-

    private int ConstructSourceDestinationFolderList()
    {
        if (Directory.Exists(txtboxSrcFolder1.Text) && Directory.Exists(txtboxDestFolder1.Text))
        {
            trans.szSourceFolderList.Add(txtboxSrcFolder1.Text.ToString());
            trans.szDestinationFolderList.Add(txtboxDestFolder1.Text);
        }
        else
        {
            return 1;
        }

        if (!String.IsNullOrWhiteSpace(txtboxSrcFolder2.Text))
        {
            if (Directory.Exists(txtboxSrcFolder2.Text) && Directory.Exists(txtboxDestFolder2.Text))
            {
                trans.szSourceFolderList.Add(txtboxSrcFolder2.Text);
                trans.szDestinationFolderList.Add(txtboxDestFolder2.Text);
            }
            else
            {
                return 1;
            }
        }


        if (!String.IsNullOrWhiteSpace(txtboxSrcFolder3.Text))
        {
            if (Directory.Exists(txtboxSrcFolder3.Text) && Directory.Exists(txtboxDestFolder3.Text))
            {
                trans.szSourceFolderList.Add(txtboxSrcFolder3.Text);
                trans.szDestinationFolderList.Add(txtboxDestFolder3.Text);
            }
            else
            {
                return 1;
            }
        }

        return 0;
    }

现在我必须对所有的文本框做同样的事情。这似乎很麻烦。有没有一种更简洁的方法来设计这种验证?

将其推广到一种可能会接受文本框文本的方法?听起来不太麻烦。我总是可以写下它,然后把它贴到我的问题上。这种方法的问题是,我通过名字访问每个文本框,因此不能只是迭代列表,使其更通用。你不需要两个测试。IsNullOrWhiteSpace也捕获空条件,这不是我要说的。您只有3对,所以只需创建一个像
boolvalidatetextboxs(string,string)
这样的方法即可完成所有工作,然后只需调用它3次,就像
if(validatetextboxs(tb1.Text,tb2.Text)){/*do stuff*/}
一样。不应该有太多的代码,我不认为。。。而且@Steve是正确的。不需要第二次检查。数字3看起来很随意。为什么不使用1和Add按钮呢。列表也需要可见,以便用户可以更正错误。现在,所有这些都变得简单易用,编写起来也同样简单。