捕获在文本框上引发离开事件的控件(按钮单击)

时间:2016-07-23 07:15:12

标签: vb.net event-handling

我有TextBoxLeave事件 在TextBox.Leave子广告中,我想显示一个确认消息,告诉用户保存更改,但是,如果我显示MsgBox,则Button.Click事件不会被触发(在{{之后) 1}}事件:请参阅我之前的问题Here

所以我想插入(在TextBox.Leave Sub中)一个代码,用于捕获被点击并触发TextBox.Leave事件的按钮的名称(或另一个rif)。

拥有按钮名称,我将能够提升点击事件:

TextBox.Leave

2 个答案:

答案 0 :(得分:1)

您可以使用方法更好地组织代码,而不是调用事件。以这种方式调用代码的一个问题是,迟早你最终想知道用户或代码是如何调用它的。

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    ' arguably, if the user clicks a save button, 
    ' you dont ask them
    SaveMyStuff()
End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    If QueryUserSave("Customer") Then
        SaveMyStuff()
    End If
End Sub
Private Function QueryUserSave(whereMsg As String) As Boolean
    Dim dlgR As DialogResult
    Dim msg = String.Format("Some stuff has changed in {0}. Save it now?", whereMsg)

    dlgR = MessageBox.Show(msg, "Sorry to bother you...", MessageBoxButtons.YesNo)

    Return dlgR = Windows.Forms.DialogResult.Yes
End Function

Private Sub SaveMyStuff()
    '...
End Sub

如果您编写的方法(包括事件)只做一件事,您可以将它们从其他方法链接在一起,一遍又一遍地重复使用它们。

答案 1 :(得分:0)

Dim CtrlName As String = Me.ActiveControl.Name