Jjstar
Jjstar

Reputation: 23

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();
}

Upvotes: 0

Views: 1626

Answers (1)

41686d6564
41686d6564

Reputation: 19661

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);
    }
    

Upvotes: 3

Related Questions