Intecpsp
Intecpsp

Reputation: 362

button.PerformClick(); not working in Form Load

I'm calling a button click in the form_load like this:

public void Form1_Load(object s, EventArgs e)
{
    button.PerformClick();
}

But upon loading the button does not get clicked, what am I doing wrong?

Upvotes: 5

Views: 16764

Answers (3)

King King
King King

Reputation: 63387

This works for me:

public void Form1_Load(object s, EventArgs e){
  button.PerformClick();
}

Looks like you didn't register the Form1_Load as event handler for the Load event of your form. Try this:

public Form1(){
   InitializeComponent();
   Load += Form1_Load;//Register the event handler so that it will work for you.
}

Upvotes: 2

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

To get the button clicked on form load, you need to fire an event after the form is loaded, try this

public Form1()
{
        InitializeComponent();
        //Event fired
        this.Load += new System.EventHandler(this.button1_Click);

}

//Event Handler 
private void button1_Click(object sender, EventArgs e)
{
    //do something
}

Upvotes: 0

Vandesh
Vandesh

Reputation: 6904

You can write whatever you want to do inside of click in another function and call that from inside the click handler or programmatically like this -

public void Form1_Load(object s, EventArgs e)
    {
        //button.PerformClick();
        PerformClickAction();
    }

void button_click(object sender,EventArgs e) 
{
    PerformClickAction();
}

void PerformClickAction()
{
    // Write what you need to do on click
}

Upvotes: 7

Related Questions