如何在c#windows Application中验证多个文本框?
问题描述:
我的注册表单中有 12个文本框,其中我想仅验证7个文本框。为此,我尝试了这段代码。
I have 12 textboxes in my registration form out of which i want to validate only 7 textboxes. for this i have tried this code.
public void ValidateFields()
{
var controls = new[] { txt_PartyName, txt_ContactPerson, txt_mobile1, txt_add, txt_city, txt_state, txt_PinCode };
foreach (var control in controls.Where(e => String.IsNullOrWhiteSpace(e.Text)))
{
errorProvider1.SetError(control, "Please fill the required field");
}
}
但是此代码无法按预期工作。我在保存按钮点击事件上调用了此功能,但效果不佳。如果实际上我把所有字段留空了,那么它也会将数据保存到数据库,即不需要。
因此,PLZ为我提供了解决此问题的帮助。
提前致谢
But this code doesn't work as expected. I have call this function on my Save button click event but it is not working well. If actually i left all the field blank then also it saves data to the database i.e not required.
So plz provide me assistance to resolve this issue.
Thanks in advance
答
将public void更改为public boolean,检测到错误后返回false,如果一直返回true则返回true。
根据您的验证结果保存。
如果(ValidateFields){
//保存到数据库
}
验证功能的新版本如果需要验证:
Change public void to public boolean, after the error is detected return false, if it goes all the way through return true.
Save depending on your validation result.
If (ValidateFields) {
// save to database
}
New version for validate function only IF ALL NEED TO VALIDATED:
public void ValidateFields()
{
var controls = new[] { txt_PartyName, txt_ContactPerson, txt_mobile1, txt_add, txt_city, txt_state, txt_PinCode };
boolean isValid = true;
foreach (var control in controls.Where(e => String.IsNullOrWhiteSpace(e.Text)))
{
errorProvider1.SetError(control, "Please fill the required field");
isValid = false;
}
return isValid;
}
如果有帮助,请带是时候接受解决方案,以便其他人可以找到它。谢谢。
If this helps, please take time to accept the solution so others may find it. Thank you.
将所有必需的文本框放在GroupBox中。
然后验证如下。
Put all required Textboxes in a GroupBox.
Then validate as below.
private void button1_Click(object sender, EventArgs e)
{
foreach (Control control in groupBox1.Controls)
{
string controlType = control.GetType().ToString();
if (controlType == "System.Windows.Forms.TextBox")
{
TextBox txtBox = (TextBox)control;
if (string.IsNullOrEmpty(txtBox.Text))
{
MessageBox.Show(txtBox.Name+ " Can not be empty");
}
}
}
}
看到这个 [ ^ ]