Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a form in UserControl

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?

like image 655
FJPoort Avatar asked Nov 23 '12 10:11

FJPoort


2 Answers

you can use

((Form)this.TopLevelControl).Close();
like image 163
Tobia Zambon Avatar answered Sep 22 '22 13:09

Tobia Zambon


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.

like image 41
Lionel D Avatar answered Sep 24 '22 13:09

Lionel D