4

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

PriceCheaperton
  • 5,071
  • 17
  • 52
  • 94

4 Answers4

8

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(); 
}
Justin Iurman
  • 18,954
  • 3
  • 35
  • 54
3

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
}
Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60
2

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");
    }
gwt
  • 2,331
  • 4
  • 37
  • 59
-1

@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

Venkatesh Ellur
  • 158
  • 1
  • 10
  • @Sergey Berezovskiy : the implementation is the same for the scenario mentioned by 'PriceCheaperton'. its just that I am into Web technologies. I have posted the solution in web forms. and the same can be implemented even in the windows forms without any C# code change. – Venkatesh Ellur Jan 11 '14 at 11:34
  • 1
    Question is tagged with *winforms* tag. Also I don't understand how screenshot of browser helps here – Sergey Berezovskiy Jan 11 '14 at 11:41