新手(一个失去焦点的问题)
弄了好长时间都没明白怎么回事。
窗体上有5个TextBox,两个功能
第一:如果第1个TextBox不为空,则第2个TextBox就不许为空
第二:如果第2个TextBox不为空,则第1个TextBox就不许为空
先不管第一个功能,先单独实现第2个功能
我给第2个TextBox写了一个失去焦点的事件
Private Sub TextBox2_ItemCheck(ByRef e As mctrls.gmFormBase.ItemCheckEventArgs) Handles TextBox2.ItemCheck
'判断如果为空则回到这个TextBox1的焦点上
If TextBox2.text <> " " Then
If TextBox1.text <> " " Then
继续执行
Else
MsgBox( "不许为空 ")
Me.TextBox1.focus()
End If
End if
End Sub
现在出现一个问题,就是当第一次离开TextBox2这个控件会触发上面的代码,但当第二次离开TextBox2这个控件的时候就不触发上面的代码了。无论是回车,按TAB,或者是直接将鼠标放到其他控件上的时候都不触发上面的代码。我想要得就是只要失去焦点就触发上面的代码。该如何实现呢??谢谢各位大虾。
[解决办法]
Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
If TextBox1.Text = " " And TextBox2.Text <> " " Then
MsgBox( "TextBox1不能为空! ")
TextBox1.Focus()
End If
End Sub
Private Sub TextBox2_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.Leave
If TextBox1.Text <> " " And TextBox2.Text = " " Then
MsgBox( "TextBox2不能为空! ")
TextBox2.Focus()
End If
End Sub
但是会有一个问题,就是一旦在一个TextBox中输入内容进入另一个TextBox后,这两个TextBox就不能为空了,因为无法同时删除两个TextBox中的内容。所以可能还要加一个用于重置的Button。
[解决办法]
用TextBox的Validating事件处理
eg.
Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If Not Me.TextBox2.Text = String.Empty Then
If Me.TextBox1.Text.Trim = String.Empty Then
e.Cancel = True
End If
End If
End Sub
Private Sub TextBox2_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox2.Validating
If Not Me.TextBox1.Text = String.Empty Then
If Me.TextBox2.Text.Trim = String.Empty Then
e.Cancel = True
End If
End If
End Sub