[英]Strange Issue Validating Empty Text Box in Winforms .NET 4.0 VB.NET
我只是将验证添加到一个新的winform中。 我正在使用验证和验证事件,以及错误提供程序控件。 请参阅下面的代码。
首次验证没问题(即,如果用户输入超过12个字符)。 在验证事件中设置错误,并且错误一直持续到用户输入12个或更少的字符。 然后输入验证事件并将错误重置为空字符串。
但是,同一文本框上的第二次验证存在问题。 代码检查文本框中的零长度..并使用提供程序设置错误。 在调试器中观察,确实调用了此代码,并将错误设置为ok。 然后发生一些奇怪的事情,经过验证的事件被(意外地)触发,并且那里的代码会立即重置错误。
为什么在已经设置错误时触发了验证事件? 这似乎是一个.NET错误。 任何人都可以建议另一种方式,或说我做错了什么?
谢谢,
巴扎
Private Sub SampleCodeTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles SampleCodeTextBox.Validating
If SampleCodeTextBox.Text.Length > 12 Then
e.Cancel = True
FormErrorProvider.SetError(SampleCodeTextBox, "Max of 12 characters for sample code")
End If
If SampleCodeTextBox.Text.Trim.Length = 0 Then
FormErrorProvider.SetError(SampleCodeTextBox, "Must enter a sample code")
End If
End Sub
Private Sub SampleCodeTextBox_Validated(sender As Object, e As System.EventArgs) Handles SampleCodeTextBox.Validated
FormErrorProvider.SetError(SampleCodeTextBox, "")
End Sub
当您的Validating事件处理程序中的零长度文本检查失败时,您需要将CancelEventArgs.Cancel
属性设置为True
。
从有关Control.Validated事件的MSDN文章:
如果在Validating事件委托中将CancelEventArgs的Cancel属性设置为true,则会禁止在Validating事件之后通常发生的所有事件。
您是不是在下一个if块中遗漏了e.Cancel = True
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.