为单个控件使用多个条件语句并在公共方法中放置条件语句

时间:2012-10-25 19:38:54

标签: c#

我正在尝试根据个别条件验证多个字段/控件。问题是我有单独的标签,表明基于特定控件而不是消息框的错误;有没有更有效的方法来做到这一点?

以下是代码:

if (txtPhone. Text. Length <= 0) 
{ 
lblPhoneRequired.Visible = true; 
} 
else 
{ 
lblPhoneRequired.Visible = false; 
}

if (txtName. Text. Length <= 0) 
{ 
lblNameRequired. Visible = true; 
} 
else 
{ 
lblNameRequired. Visible = false; 
}

最后,我尝试将其包装成这样的Public方法:

public void validation() {
if (txtPhone. Text. Length <= 0)
{ 
lblPhoneRequired.Visible = true; 
} 
else 
{ 
lblPhoneRequired.Visible = false; 
}

if (txtName. Text. Length <= 0) 
{ 
lblNameRequired. Visible = true; 
} 
else 
{ 
lblNameRequired. Visible = false; 
}
}

然后在按钮单击事件中调用该方法,但它不起作用。

private void btnSample_Click(object sender, EventArgs e) 
validation(); 
}

这是新的领域所以请忍受我的无知:

2 个答案:

答案 0 :(得分:3)

您可以缩短代码:

lblPhoneRequired.Visible = (txtPhone.Text.Length == 0); 
lblNameRequired.Visible =  (txtName.Text.Length  == 0); 

请注意,这并不比您的appoach效率更高或更低,但它更简洁,可能更具可读性。

当然,您也可以使用具有不同错误消息的单个控件:

lblError.Visible =   (txtPhone.Text.Length == 0)
                  || (txtName.Text.Length  == 0);
if((txtPhone.Text.Length == 0) && (txtName.Text.Length  == 0))
     lblError.Text = "Enter phone number and name";
else if(txtPhone.Text.Length == 0)
     lblError.Text = "Enter phone number";
else if(txtName.Text.Length == 0)
     lblError.Text = "Enter name";
else
    lblError.Text = String.Empty;

但是你应该看看每个控件都有Validating事件和CausesValidation属性。

答案 1 :(得分:0)

if (txtPhone. Text. Length <= 0)
  lblPhoneRequired.Visible = lblNameRequired. Visible = true; 
else
  lblPhoneRequired.Visible = lblNameRequired. Visible = false;