Question

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

Was it helpful?

Solution

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

OTHER TIPS

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
}

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

@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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top