PriceCheaperton
PriceCheaperton

Reputation: 5379

How to click a button on form load using C#

How do i click a button on foam load using C#? My button is called: btnFacebookLogin

I have tried this following:

private void Form1_Shown(Object sender, EventArgs e) 
{
   btnFacebookLogin.PerformClick(); 
}

I am using WinForms C# .NET 4

Upvotes: 4

Views: 21412

Answers (4)

Venkatesh Ellur
Venkatesh Ellur

Reputation: 158

@PriceCheaperton : you can call an event from another event the simplest example is here.

C# :

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1_Click(sender, e);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("Calling event from an event...");
    }
}

ASPX :

<body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>

Output : enter image description here

Upvotes: -1

Justin Iurman
Justin Iurman

Reputation: 19026

Be sure to link your handler after InitializeComponent() and to Load event

public Form1()
{
   InitializeComponent();
   Load += Form1_Shown;
}

private void Form1_Shown(Object sender, EventArgs e) 
{
   btnFacebookLogin.PerformClick(); 
}

Upvotes: 8

Obsidian Phoenix
Obsidian Phoenix

Reputation: 4155

Is there a specific reason you need to actually click the button?

I would just move the code in the click event into a function, then call that function from both the load event and the click event. It will get around the need to call click()

For instance:

private void Form1_Shown(Object sender, EventArgs e) 
{
   DoFacebookLogin();
}

private void btnFacebookLogin_Click(Object sender, EventArgs e)
{
    DoFacebookLogin();
}

private void DoFacebookLogin()
{
    //Do Work here
}

Upvotes: 3

gwt
gwt

Reputation: 2423

You can do this :

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

And I consider that you know that the following event handler should exist in your code behind :

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("hi");
    }

Upvotes: 2

Related Questions