7

I created a UserControl with the buttons Save, Close and Cancel. I want to close the form without saving on the Cancel button, prompt a message to save on the Close button and Save without closing on the Save button. Normally, I would have used this.Close() on the Cancel button, but the UserControl doesn't have such an option. So I guess I have to set a property for that.

Scrolling down the "Questions that may already have your answer" section, I came across this question: How to close a ChildWindow from an UserControl button loaded inside it? I used the following C# code:

private void btnCancel_Click(object sender, EventArgs e)
{
    ProjectInfo infoScreen = (ProjectInfo)this.Parent;
    infoScreen.Close();
}

This does the job for one screen, but I wonder if I have to apply this code for all the screen I have? I think there should be a more efficient way. So my question is: Do I need to apply this code for every form I have, or is there another (more efficient) way?

1
  • Controls should not mess with their parent, raise an event instead. Nov 23, 2012 at 11:41

4 Answers 4

25

you can use

((Form)this.TopLevelControl).Close();
1
  • Mine answer did the trick for what I use it for (indeed the control is directly embedded in the form). But I like yours better
    – FJPoort
    Nov 26, 2012 at 10:52
7

you can use the FindForm method available for any control:

private void btnCancel_Click(object sender, EventArgs e)
{
    Form tmp = this.FindForm();
    tmp.Close();
    tmp.Dispose();
}

Do not forget to Dispose the form to release resources.

Hope this helps.

1
  • You helped my life. Thanks alot May 25, 2019 at 21:29
1

You also can close one form in any part of the code using a remote thread:

            MyNamespace.MyForm FormThread = (MyNamespace.MyForm)Application.OpenForms["MyForm"];
            FormThread.Close();
0

I found the simple answer :) I all ready thought of something like that.

To close a WinForm in a ButtonClicked Event inside a UserControl use the following code:

private void btnCancel_Click(object sender, EventArgs e)
{
    Form someForm = (Form)this.Parent;
    someForm.Close();
}
1
  • it depends if the usercontrol is directly embedded in the form or in other sub-controls. using TopLevelControl should make the trick Nov 23, 2012 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.