genespos genespos - 4 months ago 16
Vb.net Question

Button.Click event doesn't fire after TextBox.Leave event

I use the below code to verify if the text into a TextBox was changed and ask for saving changes:

Private TBoxTxtBefore As String = String.Empty

Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
Try
TBoxTxtBefore = CType(sender, TextBox).Text
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
Try
If CType(sender, TextBox).Text <> TBoxTxtBefore Then
Dim SN As MsgBoxResult = MsgBox("Save changes?", vbYesNo, "Save Changes")
If SN = vbYes Then Btn_SaveChanges.PerformClick()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub


But when I click a button (for example
button1
) while the cursor is inside
TextBox1
, only
TextBox1.Leave
event was raised.

How can I have
Button?.click
event raise after
TextBox1.Leave
event?

Answer

How can I have button1.click event raise after TextBox1.Leave event?

If TextBox1 has the focus and you click a button the leave event will fire before the click event. To test click in Texbox1, then click Button1.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Debug.WriteLine("B1C")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Debug.WriteLine("B2C")
End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    Debug.WriteLine("TBL")
    Button2.PerformClick()
End Sub

Try to clarify your question please.

edit: This recreates the problem I think you are having,

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Debug.WriteLine("B1C")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Debug.WriteLine("B2C")
End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    MessageBox.Show("FOO")
    Debug.WriteLine("TBL")
    Button2.PerformClick()
End Sub

Did some searching and found that the Message box causes pending focus events to be lost.

Comments