Share via

How to close usecontrol window?

melisa onur 1 Reputation point
2021-05-25T11:44:07.177+00:00

I want the usercontrol window to close when the button on the usercontrol is clicked. How do I do this? I tried this.hide or this.dispose, but when I use them, the buttons in my form window are not visible.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,661 Reputation points
    2021-05-26T03:15:18.67+00:00

    Hi melisaonur-4906,
    >>I tried this.hide or this.dispose, but when I use them, the buttons in my form window are not visible.

    Are you referring to the button on the usercontrol?
    I have two suggestions for you to refer to:

    1. Add usercontrol and button controls by coding.
      You can refer to the following code: UserControl userControl = new UserControl();
      private void Form1_Load(object sender, EventArgs e)
      {
      Button button = new Button();
      button.Click += new EventHandler(click);
      userControl.Controls.Add(button);
      button.BackColor = Color.Red;
      userControl.BackColor = Color.Green;
      this.Controls.Add(userControl);
      }
      public void click(object sender, EventArgs e)
      {
      userControl.Hide();
      }

    2.When adding usercontrol visually, make sure that the user control and the main forms have the same "using" references.

    using DocumentFormat.OpenXml.Packaging;  
    using DocumentFormat.OpenXml.Spreadsheet;  
    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Data;  
    using System.Drawing;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    using System.Windows.Forms;  
    
    namespace WindowsFormsApp  
    {  
        public partial class UserControl1 : UserControl  
        {  
            ......  
            private void button1_Click(object sender, EventArgs e)  
            {  
                this.Hide();  
            }  
        }  
    }  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

  2. Viorel 127K Reputation points
    2021-05-25T12:48:38.877+00:00

    Try another instruction: this.FindForm( ).Close( ).

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.