Search code examples
vb.netsender

Which button was clicked to open form


I have a form that loads from a click of any of three buttons (Add, Modify or Delete). When the form loads there is a 'Confirm' button which will perform a task depending on which button was originally used to show the form.

Is there an easy way to determine which button was originally clicked so that the right code can be executed?

Thanks


Solution

  • Well suppose to define at the global level an enum like this

    Public Enum CommandAction
        Create
        Modify 
        Delete
    End Enum
    

    Now in the code used to launch your second form to execute the Add command, you could write code like this (of course you repeat the same but varying the CommandAction in the other buttons).

    Dim myFormInstance = new MyForm(CommandAction.Create)
    myFormInstance.ShowDialog()
    

    Finally, add a specfic constructor for your second form (MyForm in this example). A constructor that receives and saves for future usage a CommandAction

    Public Class MyForm
        Dim cmd as CommandAction
    
        Public Sub New(command as CommandAction )
             InitializeComponent()
             cmd = command
        End Sub
        Public Sub New()
             InitializeComponent()
             cmd = CommandAction.Create ' Set a default'
        End Sub
    End Class
    

    Now in the code where you need to decide which kind of action to execute, just look at the value of the global cmd variable and execute the appropriate block of code

    NOTE Adding a specific constructor to a form class requires the explicit presence of the standard empty constructor.