C# Auto click button and auto fill form

This tutorial will show you how to auto fill forms and click buttons in a website using the webBrowser control. When you learn to do this you can make your own web bots!

da-app

To show you how autoclick/autofill works we’ll make a simple Google AutoSearch Bot.

So lets begin…

First of all, add a webBrowser control to your form. Set its “Url” property to “www.google.com”.

Now we’ll add two methods SetText() and ClickButton(). SetText() method will automatically fill a textBox and the ClickButton() will click the submit button.

Since we are making a Google AutoSearch Bot we need to find what’s the name of the Google search textBox and the submit button. To find these, visit Google.com from your browser and view the page source.

Here’s the code for the SetText() method:

// Set value for the attribute that has the name (attName)

void SetText(string attribute, string attName, string value)
 {

 // Get a collection of all the tags with name "input";

 HtmlElementCollection tagsCollection = webBrowser1.Document.GetElementsByTagName("input");

 foreach (HtmlElement currentTag in tagsCollection)
 {

 // If the attribute of the current tag has the name attName

   if (currentTag.GetAttribute(attribute).Equals(attName))

 // Then set its attribute "value".

   currentTag.SetAttribute("value", value);
 }
}

And now the code for the ClickButton() method:

// Click the button whose attribute has a name "attName"

 void ClickButton(string attribute, string attName)
 {
    HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("input");

    foreach (HtmlElement element in col)
    {
      if (element.GetAttribute(attribute).Equals(attName))
      {

      // Invoke the "Click" member of the button
      element.InvokeMember("click");
      }
    }
 }

Now that the main methods are added we can now tell the bot what to do :) .

Declare “bool searched = false” at Class-level (i.e add it above pulic Form1() {……). We’ll use it to check whether we have already searched or not.

Add DoucmentComplete event for the webBrowser. DocumentComplete event is fired when the page is loaded completely.

Use this code:

Note: The name of the Google search textBox is “q” and the submit buttons is “btnG”.

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
 {

 // Check if already searched

 if(searched == false)
 {

 // Set the text to "Search Text Here" of the textBox whose "name" attribute is "q";

 SetText("name", "q", "Search Text Here");

 // Click the button whose name attribute is "btnG"

 ClickButton("name", "btnG");

 // Since we have already searched, set it to true

 searched = true;

 }
 }

That’s it! Debug the project and watch the bot :)

If you have any questions don’t hesitate to post a comment.

Thanks

57 thoughts on “C# Auto click button and auto fill form

  1. Awesome. The set value doesnt work for combo-boxes. Which is a bit of a pain since if you did this via javascript, it’s just setting the value for it.

    But these ways are much faster/easier then developing using the mshtml library.

  2. Hi,

    I am working on a simple application to sign in and submit information to some of the websites. I have a web browser, listbox and textboxes on the form. I have a list of URLs in the listbox and username, password in the textboxes. When I click any item on the listbox, web browser opens that webpage.

    Now, I need to fill the related login information and submit. I am having difficulty on this, can you suggest me anything?

  3. Great job bro,

    But you should fix the quotes at the bottom , for example: ClickButton(“name’, ‘btnG”);

    Have them be double qoutes , i struggled with this for a full hour as it wont compile with single ones and it throws some crazy errors in.

    Everything is working like a charm and your tutotorial is the best!

    Kind Regards,
    Furio

  4. You can use this method to click a span:

    // The Method:

    void ClickSpan(string attribute, string attName)
    {
    HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName(“span”);

    foreach (HtmlElement element in col)
    {
    if (element.GetAttribute(attribute).Equals(attName))
    {
    element.InvokeMember(“click”);
    }
    }
    }

    // Example use:

    ClickSpan(“class”, “yt-uix-button-content”);

    Thanks

  5. HELP FOR READING ELEMENTS IN THE AJAX PANEL?!

    Hi
    thanks, its very use full for me

    i have a web application that using ajax panel
    i use this method to login the web app.
    and going to my goal page, fill the related controls
    and finally click the SUBMIT button

    after submit, web app. get data from DB and show in the page
    IN THE AJAX PANEL

    and when i want to read the element that filled after submit, the element is EMPTY!!!
    and when i watching it in VIEW SOURCE with browser it also empty BUT it is showing in the monitor???!!!!!!!

    please help me
    thanks

  6. Web App. Code sample

    .
    .Some controls
    . Search BUTTON and TEXT BOX
    .

    .
    .

    .
    .

    I can navigate to this page and fill the search textbox and click the search button with the your sample code (its work fine)
    but after that when web app. fill the Label(“APT_NAME”), webBrowser1_DocumentCompleted does not raise
    and when I see VIEW SOURCE i found my label here

    offcourse i raise it manualy after my search Button clicked

    but element value is empty

    i try AxWebBrowser and its the same!
    is that possible to catch o access elements values where updates with ajax?
    thanks

  7. corrected HTML tags ( * for & g t and & l t and \ as slashs)
    Web App. Code sample

    *asp:ScriptManager ID=”ScriptManager1″ runat=”server”*
    *\asp:ScriptManager*
    *table width=”100%”*
    *tr*
    *td align=”center”*
    *asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”*
    *ContentTemplate*
    *table width=”100%”*
    .
    .Some controls
    . Search BUTTON and TEXT BOX
    .
    *tr
    *td
    *asp:Label ID=”APT_NAME” runat=”server”* *\asp:Label*
    *\td
    *\tr
    .
    .
    *\table*
    *\ContentTemplate*
    *\asp:UpdatePanel*
    .
    .

    I can navigate to this page and fill the search textbox and click the search button with the your sample code (its work fine)
    but after that when web app. fill the Label(“APT_NAME”), webBrowser1_DocumentCompleted does not raise
    and when I see VIEW SOURCE i found my label here

    *td style=”width: 25%; height: 14px;” align=”right”*
    *span id=”ctl00_ContentPlaceHolder1_MobileFileInfo2_APT_NAME”* *\span*
    *\td*

    offcourse i raise it manualy after my search Button clicked

    but element value is empty

    i try AxWebBrowser and its the same!
    is that possible to catch o access elements values where updates with ajax?
    thanks

  8. I am developing AutoWebFormFiller using C#, I have completed it almost but unable to auto fill input file field. I want image file found in my local D Drive to be auto selected in input file field.

  9. Ok.

    I got this work. Wrote a new function to fill values in Combo boxes and works like a charm. Thanks dude :)

    Here is the code

    public void SetComboText(string attribute, string attName, string value)
    {
    // Get a collection of all the tags with name “input”;
    HtmlElementCollection tagsCollection = webBrowser.Document.GetElementsByTagName(“select”);

    foreach (HtmlElement currentTag in tagsCollection)
    {
    // If the attribute of the current tag has the name attName
    if (currentTag.GetAttribute(attribute).Equals(attName))
    // Then set its attribute “value”.
    currentTag.SetAttribute(“value”, value);
    }
    }

  10. Error:- Object reference not set to an instance of an object

    for the following line in the code

    HtmlElementCollection tagsCollection = webBrowser1.Document.GetElementsByTagName(“input”);

    • The element that you are looking for might not exist. Confirm that its not null before using it:

      // 0 is the object index. It can be anything.
      if (tagsCollection[0] != null)
      {
      // do something
      }

  11. Hi farooq,
    Im using asp.net c#. I have one drop-down list which is internship type and another is a text box which is country. Example I select local under the internship type from the drop down list, the textbox which is the country should be automatically state singapore. When I select overseas under the internship type from the drop down list, the text box should be automatically state other country which is not singapore. How can I do it?? Any help will be highly appreciated.

    Thank you,
    Sara

  12. Hey guys,

    I am unable to click textboxes available on yahoo new account creationg form.

    I want to click the firstname, lastname etc textbox on yahoo’s new account creation page but when I click a textbox, code doesn’t pick that textbox rather it picks some division. Could you please try

    URL:
    http://bit.ly/u3eXM1

    Remember, I want to click the textbox not the button

  13. hi

    What about if you have X sites…

    Site 1: fill in click go to Site 2
    Site 2: click on site3..
    Site 3: click on finished

    how do you know when site 2/site 3 is loaded? (i have page that load’s 3 times WebBrowserDocumentCompletedEventArgs :S .. i think it’s ajax)

    gr.

  14. Able to use/adapt for a variety of web sites (google, yahoo, etc.). Extremely useful..thanks.

    Am stumped as to why code does not find TagName “input” in html snippet below. As a result, I’m unable to autofill username. Thanks for any assist.

    Domain\user name:

  15. Thanks for excellent post. Could you address how to obtain input ids for OWA (outlook web access). It seems that getelementsbytagname does not work…returns count=0 tagnames found (see snippet below).

  16. Hey

    First of all, this tutorial is so awesome, worked like a charm, the only thing i got a problem with now, is comboboxes, do u think u could give me an example

    nevertheless, good job and that u so much

  17. Plz help me Fill in ID 1589ed7d370641d8b71e619a222013dac and 107750810ce2cd3b0744f5d08fffbe248. Thanks you!

    Username

    Password

  18. Sorry again! I do’nt know why my post was not full.
    how can I click this image ?

    img style=”cursor: pointer;” src=”/images.jpg” onclick=’this.src=”/captcha.jpg”;>Username

    and fill in ID?
    <div class="form_value
    input class="form_input" onfocus="osk_field=this;" name="1bcec52c08c411fddbce9bee639c8e933" id="1bcec52c08c411fddbce9bee639c8e933" value="" type="text

    Thanks you to answer!

  19. Hi,

    I’m trying to use this code, I’m really happy to have found it but I’m facing some issues.

    I can’t use this code because of my System.Windows.Forms.dll
    I’ve already add the reference but into my System.windows.forms.dll it seems there is no definition for GetEllementByTagName(“”); What can i Do?

    I hope you will answer. and I Hope this answer will help me.

    Thanks a lot

  20. I’ m glad to meet this kind of source code because I needed it, But I’ve issues which might seems to be stupid but my Visual studio is telling me that I need a using reférence which is the réference to System.Windows.Forms so I gave him the .dll file but He is telling me that There is no definitions for this method
    GetElementsByTagName(“input”);

    I hope you will be able to help me, Waiting for an answer .

    Bye

  21. Thanks for sharing..this works like charms…

    Can we make this genric type…lets say.two sites having different naming convention for input box..

    E.g. on yahoo..input field name is txtname while on gmail it is textname /name…how can we do generic kind of site input box filling..(e.g. Roboform utility)…

    Thanks
    Bye

  22. Hi, Thanks for sharing this.

    Normally on different sites, Tagvalue / Name /Id can vary.

    E.g. in site X, field name could be txt_name and on site Y it could be reg_name. Any Idea, how we can write generic code based on the label / Description instead of Tag names.

    Thanks

  23. Hi
    this is a great post, but i’d like to know how to do it in php (i’m kind of newbie in PHP) can you show me please?

    thanks

  24. thanks,
    is there a way to click a button which has no name?
    I have tried many things but failed,
    ex:
    webBrowser1.Document.GetElementById(“button”).InvokeMember(“click”);

    The buttons Probs from the Site is:
    class = ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover ui-state-focus

    role = button

    aria-disabled = false

    Position:
    Links: 1010px Oben: 283px
    Breite: 81px Höhe: 24px

    Other:
    Schriftart: Verdana,Arial,sans-serif
    Schriftgröße: 11px

    Parrentelemente:

    html

    body

    div #wrap

    div #content-middle

    form

    table

    tbody

    tr

    td

    Childlemente

    span .ui-button-text

    Please help me

  25. Thanks! But could you also show how to fill in forms that have comboboxes, radiobuttons, checkboxes? Also, if a form opens a new window and I would like to fill in that too, how do I navigate to that new window? Do I also use the Url property of webBrowser control?

  26. Unfortunately all attempts to use this code seem to be a bust for me. I have updated my code as the button is now listed as btnK, but ultimately nothing fills, and nothing searches.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>