在c#visual studio中验证必填字段和确认字段

时间:2014-12-08 04:16:49

标签: c# winforms

我在创建需要用户在字段中输入信息的表单时遇到问题,确认电子邮件和密码输入,并在匹配/填写所有这些字段时转到下一个表单。单独地,代码I有工作,但我似乎无法找到一种方法,以便在进入下一个表格之前满足所有要求。如果我点击继续按钮,它现在只是进入下一个表格。

我的代码的一些摘录是:

if (string.IsNullOrEmpty(email))
{
    lblRequirementsError.Text = ("All required fields have not been filled.");
}

if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
    lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}

if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
    lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}

this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();

5 个答案:

答案 0 :(得分:0)

if (! txtBoxEmail.Text.Equals( txtBoxConfirmEmail.Text))
{
    lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}

if (! txtBoxPassword.Text.Equals( txtBoxConfirmPassword.Text))
{
    lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}

答案 1 :(得分:0)

您是否在Visual Studio 2012中使用Web应用程序表单。您可以在.ASPX文件中使用字段验证程序,以便在表单提交之前验证您要验证的任何字段。用C#编写所有内容要容易得多。

答案 2 :(得分:0)

如果要绑定控件或将控件转换为数据对象,则可以使用DataAnnotation。然后很容易验证。请参阅链接了解更多详情

http://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx

答案 3 :(得分:0)

问题是无论if结果如何,都会创建和打开表单,因为它的代码在ifs之外。首先,检查没有字段为空,然后检查是否已满足验证,然后打开新窗口。这样的事情应该有效:

//If both email and password are not empty
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
    //if both email and password math the re entry
    if (txtBoxEmail.Text == txtBoxConfirmEmail.Text &&
        txtBoxPassword.Text == txtBoxConfirmPassword.Text)
    {
        //execute the code to open the new form
        this.Hide();
        frmBilling secondForm = new frmBilling();
        secondForm.Show();
    }
}

答案 4 :(得分:0)

试试这个:

bool validationStatus = default(bool);

if (string.IsNullOrEmpty(email))
{
    lblRequirementsError.Text = ("All required fields have not been filled.");
    validationStatus  = true;
}

if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
    lblEmailError.Text = ("Email reentry does not match. Please reenter.");
    validationStatus  = true;
}

if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
    lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
    validationStatus  = true;
}

if(!validationStatus)
{
   Hide();
   frmBilling secondForm = new frmBilling();
   secondForm.Show();
}