0

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

这是代码:

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 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(); 
}

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

盖伊

4

2 回答 2

3

你可以缩短你的代码:

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

请注意,这并不比您的方法效率更高或更低,但它不那么冗长并且可能更具可读性。

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

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

于 2012-10-25T19:40:29.637 回答
0
if (txtPhone. Text. Length <= 0)
  lblPhoneRequired.Visible = lblNameRequired. Visible = true; 
else
  lblPhoneRequired.Visible = lblNameRequired. Visible = false; 
于 2012-10-25T19:46:32.410 回答