User Control Buttons to Close a Dialog Box

Taryn picture Taryn · Mar 16, 2011 · Viewed 12k times · Source

I have created a User Control in my application that has a textbox and then 2 buttons on it. One button is to Add data to the DB from the textbox and the second Cancels the action. This User Control is then added to multiple Dialogs (forms) but I want the buttons to trigger the same events, which the reason I placed the buttons on the User Control and not the Dialog.

What I am trying to do is after they click the Add data button and it is successful, I want it to close the Dialog that the control is located on.

EDIT:

I don't know how to go about coding this to close the Dialog when it is triggered from a User Control. I don't know where to start because I haven't used User Controls before. Typically I just have the controls on a Dialog which allows for the DialogResult = DialogResult.OK;

Thanks

Answer

Iain Ward picture Iain Ward · Mar 16, 2011

Forms opened modally will close automatically when their DialogResult is set. From the sounds of it, you are setting the DialogResult of the control, not the form. To do what are you are trying to do, you need the control to set or trigger the setting of the parent forms dialog result. You can do this by either:

1. Passing through a reference of the form to the control, which allows the control to set it.

2. Create an event on the control that the forms listens to, which tells it to close. (recomemnded way)

3. (The hacky way) Set the forms dialog result using this code:

this.ParentForm.DialogResult = DialogResult.OK;

The form will also need to be shown modally, otherwise you will need to call the Close() method manually.