Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a form click a button when loaded?

I have 2 forms – Mainmenu form , that clicks to a registration from.

On the registration form, I have a button. I want the form to automatically click when the form is loaded. Below is what I have tried so far but it doesn’t work. Any suggestions?

public Membershipform()
{
    InitializeComponent();
    Button_1.PerformClick();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you’re calling PerformClick() in the Form’s constructor. At which point, the Visible property of the Button is false, causing PerformClick() to fail because in order for it to work, both the Visible and Enabled properties of the button must be true. You can confirm this by checking the source.

Your options:

  1. Move the call to PerformClick() to the Load event of the form.

    private void Membershipform_Load(object sender, EventArgs e)
    {
        Button_1.PerformClick();
    }
    
  2. Move the code in the button’s Click event handler to a separate method and call that method from the constructor.

    public Membershipform()
    {
        InitializeComponent();
        DoSomething();
    }
    
    private void DoSomething()
    {
        // Code that was originally in Button_1_Click
    }
    
    private void Button_1_Click(object sender, EventArgs e)
    {
        DoSomething();
    }
    
  3. Call Button_1_Click directly from the form constructor:

    public Membershipform()
    {
        InitializeComponent();
        Button_1_Click(null, EventArgs.Empty);
    }
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading