如何验证 C# WF 中的文本框?
How to validate textbox in C# WF?
我有两个 windows 形式的文本框。
还有一个禁用按钮。
如何验证文本框:
- 如果字段为空则禁用按钮
- 如果字段内的值小于 5,则禁用按钮
- 其他情况 - 启用按钮
我在事件 TextChange 上试过这个,但是当我尝试输入值时 43
我收到通知,因为事件 TextChange
在每次输入符号后起作用。
代码:
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox2.Text))
{
button6.Enabled = true;
}
}
如果您不想在每次按下键时都进行验证,而是希望在用户离开该字段时进行验证,而不是挂接到 TextChanged
事件,请挂接到 Leave
事件。
private void textBox2_Leave(object sender, EventArgs e)
{
button6.Enabled = !(string.IsNullOrEmpty(textBox2.Text)) && textBox2.Text.Length >= 5;
if (!button6.Enabled)
{
textBox2.Focus();
}
}
像这样更新您的事件句柄:
private void textBox2_TextChanged(object sender, EventArgs e)
{
button6.Enabled =
!String.IsNullOrEmpty(textBox2.Text) && textBox2.Text.Length > 5
}
关于启动时禁用按钮,您只需将按钮6设置为默认禁用即可。
或者,在构造函数中调用验证:
textBox2_TextChanged(null, null);
TextChanged
和 Leave
事件都不适合这个。正确的事件称为(惊喜:-)Validating
。如果验证错误,您需要设置 e.Cancel = true
。更多信息:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx
我有两个 windows 形式的文本框。 还有一个禁用按钮。
如何验证文本框:
- 如果字段为空则禁用按钮
- 如果字段内的值小于 5,则禁用按钮
- 其他情况 - 启用按钮
我在事件 TextChange 上试过这个,但是当我尝试输入值时 43
我收到通知,因为事件 TextChange
在每次输入符号后起作用。
代码:
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox2.Text))
{
button6.Enabled = true;
}
}
如果您不想在每次按下键时都进行验证,而是希望在用户离开该字段时进行验证,而不是挂接到 TextChanged
事件,请挂接到 Leave
事件。
private void textBox2_Leave(object sender, EventArgs e)
{
button6.Enabled = !(string.IsNullOrEmpty(textBox2.Text)) && textBox2.Text.Length >= 5;
if (!button6.Enabled)
{
textBox2.Focus();
}
}
像这样更新您的事件句柄:
private void textBox2_TextChanged(object sender, EventArgs e)
{
button6.Enabled =
!String.IsNullOrEmpty(textBox2.Text) && textBox2.Text.Length > 5
}
关于启动时禁用按钮,您只需将按钮6设置为默认禁用即可。
或者,在构造函数中调用验证:
textBox2_TextChanged(null, null);
TextChanged
和 Leave
事件都不适合这个。正确的事件称为(惊喜:-)Validating
。如果验证错误,您需要设置 e.Cancel = true
。更多信息:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx