Catch the control (button click) who raised the leave event on a textbox

筅森魡賤 提交于 2019-12-11 18:08:59

问题


I have a TextBox with Leave event.
In the TextBox.Leave sub, I would like to show a confirmation MsgBox to ask user for saving changes but, if I show a MsgBox, the Button.Click event isn't fired (after TextBox.Leave event: see my previous question Here)

So I thought to insert (in the TextBox.Leave Sub) a code for catching the name (or another rif) of the button that was clicked and fired TextBox.Leave event.

Having the button name, I'll be able to raise the click event:

DirectCast(Me.Controls("ButtonName"), Button).PerformClick()

回答1:


Rather than invoking events, you can use methods to organize the code better. One of the problems of invoking code that way is that sooner or later you end up wanting to know how it was invoked by the user or code.

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

If you write methods (which includes events) which do one single thing, you can link them together from other methods to reuse them over and over.




回答2:


Dim CtrlName As String = Me.ActiveControl.Name


来源:https://stackoverflow.com/questions/38539211/catch-the-control-button-click-who-raised-the-leave-event-on-a-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!