Which button closed the form?

kokas

Member
Joined
Jul 21, 2005
Messages
12
Programming Experience
1-3
Hello

I want to find which button on my form caused it to close through the Form_Closing event. In the button's Click event i have this:

Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()

End Sub

And in the Closing event:

Private Sub frmCandDetails_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing

now when i use sender.gettype here i always get the form itself...how can i go one step back to see who caused this event? VB6 had a QueryUnload method that is non existent in .NET. Could it be done through Delegates?

 
If your form has been diplayed using ShowDialog, you can assign a DialogResult to each Button and then the form's DialogResult property, which will be the same as the return value of ShowDialog, will match the DialogResult property of the Button that was clicked.

The Closing event you are handling is raised on the form itself, so of course the sender is the form. If you want to know what button was clicked using your current method then you need a class-level variable that is set in each Button's Click event handler. The variable could be of type Button and each Button could set it to itself:
VB.NET:
Private closingButton As Button

Private Sub btnClose_Click(...) Handles btnClose.Click
	Me.closingButton = DirectCast(sender, Button)
	Me.Close()
End Sub

Private Sub frmCandDetails_Closing(...) Handles MyBase.Closing
	If Me.closingButton Is Me.btnClose Then
		'Do something here.
	End If
End Sub
Notice that I do not refer to a specific member in the Click event handler but rather cast the sender. This allows you to create one event handler for all the Buttons. Note that one procedure can handle more than one event, and several procedures can handle the same event. If you have more than one procedure to handle the same event, they will be called in the same order that you created them, so make sure that you create them in the same order that you want them to be executed in. For instance, you could write one procedure to handle the Click event for several buttons in which the closingButton variable is set. You could then write individual procedures for each button in which you do whatever is required by each particular command.
 
Public variable

You can declare some public variable and then test to see which one closed button:

- in module
Public FormCloser as String

-button click event
FormCloser = Me.ButtonName.Name

-testing
select case FormCloser
case "Button1"
...
end select

But I think that solution above is much more elegant.
 
Thanks guys. I had already done the 2nd solution and it worked fine. I will try the harder 1st one and let u know.
 
Back
Top