Hi Im trying to get this code to fill in the forms (works without the code making the error) i have tried and tried but i have no clue
can you please point out the problem and show me the solution or a fix i am being pushed to the point for something so simple well it should be :P

webBrowser1.Document.GetElementById("*******").InvokeMember("click");

and the error is;

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=*******
  StackTrace:
       at Ping_O_Matic.Form1.button2_Click(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Ping_O_Matic.Program.Main()
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

my source code below!
-----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ******
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("*********");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            webBrowser1.Document.GetElementById("title").SetAttribute("value", T1.Text);
            webBrowser1.Document.GetElementById("blogurl").SetAttribute("value", T2.Text);
       



        }

        private void button2_Click(object sender, EventArgs e)
        {
          webBrowser1.Document.GetElementById("********").InvokeMember("click");
        }
    }
}

Recommended Answers

All 46 Replies

At a guess i would say your element isnt being found. Have you double checked the ID of the page once it is loaded? Bearing in mind that id's often have the ID of their container appended to their own ID to ensure uniqueness; ie, a button with ID = "button1" could end up with ID = "ctl00_panel1_button1".

You could include a check to ensure the element is found before invoking on it to prevent the exception:

HtmlElement button = webBrowser1.Document.GetElementById("ButtonID");
if (button != null)
    button.InvokeMember("click");

You are right that code stops it from throwing the error now it just doesn't click it 0.o on http://pingomatic.com/ im trying to get it to click the "send pings" button (at the bottom) i got the id by right clicking it in google chrome and selecting inspect element and i got the id chrome told me this

<a href="javascript:document.getElementById('pingform').submit()" class="bigbutton"><span>Send Pings »</span></a>

so i guess the element id is "pingform" correct but can c# click a javascript button
i think that may be the problem

Thanks Very much

What you are looking at isnt a button. Its a span with an anchor which calls a javascript function. If you look at the javascript you'll see that when the user clicks the link it invokes the Submit function on the "pingform" element. pingform is the name of the Form.
You just need to do the same:

HtmlElement elem =  webBrowser1.Document.GetElementById("pingform");
    elem.InvokeMember("submit");

i added that code now i get another problem
for webBrowser1.Document.GetElementById("title").SetAttribute("value", T1.Text);
the id is fully correct though this is really confusing

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=Ping-O-Matic
  StackTrace:
       at Ping_O_Matic.Form1.webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e) in C:\Users\Jeza\Documents\Visual Studio 2010\Projects\Ping-O-Matic\Ping-O-Matic\Form1.cs:line 29
       at System.Windows.Forms.WebBrowser.OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
       at System.Windows.Forms.WebBrowser.WebBrowserEvent.DocumentComplete(Object pDisp, Object& urlObject)
  InnerException:

A big thanks if i can get this small code to actually run correctly ):

are you calling it before or after you submit the form? If you submit the form, then its possible the page redirects and the element is no longer present.

i have it so the first button writes to the text boxes on the site
then i have another button what submits it

when the submit button is pressed it is redirected to a new page

OK, did the first button work before you changed the submit code?

The first button works fills in the form (i can see the webbrowser in the window)
but then when i click the next button what auto presses the submit button it returns that error

You say that the first button works and fills the form, but you also said that you get an error when you try to set the title on the form. Can you post your full code so i can see exactly whats happening?

it fills all the forms correctly the title ect
but when i press the next button what submit the page it gives me the error so not to sure

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Ping_O_Matic
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://pingomatic.com/");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            webBrowser1.Document.GetElementById("title").SetAttribute("value", T1.Text);
            webBrowser1.Document.GetElementById("blogurl").SetAttribute("value", T2.Text);
            HtmlElement button = webBrowser1.Document.GetElementById("checkall");
            if (button != null)
                button.InvokeMember("click");
       



        }

        private void button2_Click(object sender, EventArgs e)
        {
            HtmlElement elem = webBrowser1.Document.GetElementById("pingform");
            elem.InvokeMember("submit");
        }
    }
}

I see the problem. Your First button doesnt fill the form, it navigates to the webpage. You are then populating the form values in the DocumentCompleted event.
The problem is, when you click the second button to submit the form it causes the page to submit and reload. If the reloaded page is not the same as the first page then the elements arent there and your exception is thrown.
You need to move the code out of the DocumentCompleted event and into a seperate method. You could have anotehr button so Button1 loads the page, Button2 fills out the form and Button3 submits it.
If you want to ensure the user doesnt try filling out the form before it is loaded you can start with Button2.Enabled = false then use the DocumentCompleted event to switch Button2.Enabled = true. You can also check to see if the "title" element exists before enabling the button, that way if the page loaded isnt the correct one the button cant be clicked.

Have a go at the changes and let me know how you get on

Hi

are these changes correct because it is still throwing a bad error

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Ping_O_Matic
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://pingomatic.com/");
            button2.Enabled = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            
            webBrowser1.Document.GetElementById("title").SetAttribute("value", T1.Text);
            webBrowser1.Document.GetElementById("blogurl").SetAttribute("value", T2.Text);
            HtmlElement button = webBrowser1.Document.GetElementById("checkall");
            if (button != null)
                button.InvokeMember("click");
        }

        private void button2_Click(object sender, EventArgs e)
        {

            HtmlElement elem = webBrowser1.Document.GetElementById("pingform");
            elem.InvokeMember("submit");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            button2.Enabled = true;
        }

        
            
       



        }

        

    }

Sorry, i think i may have got you muddled with the button names. I said to have three buttons, button1 to load form, button2 to fill form and button3 to submit form. So You need to enable/disable the button that fills in the form. In your case thats button3.
What is the exact sequence that results in the exception and what is the error?
ie, Load program, click button1, wait for page load, click button2, etc....

just checked now it wont even connect to the site now???
and the error before i could not connect to the site via the program was
the submit button

im getting confused now by the disable enable ect also

Ive just knocked together a test app with your code and it all runs fine so the only problem i can imagine is that you are clicking the button to populate the form either before it finishes loading (hence the enabled/disabled switch i suggested) or you are clicking it again after submitting the form.

How are you running your program? Are you launching it in Visual Studio or are you running the EXE file in the output directory?

the page is finished loading when it appears and after like 10 seconds then i clicked it the page should be loaded by then but now i wont even connect to the site in the web browser?

using it in visual studio via debug

So you run program, press button1..page loads, you press button3 and it crashes.
Have you changed any code or settings in the designer? I dont understand where your problem could be stemming from because i copied your code into my own app and it submitted the form correctly.

well i press one to load page two to fill in forms and 3 and it crashes
i haven't changed anything it just stopped?

Ok, i think i see what might be going on here. Coding Lesson 1: Use meaningful names.
Whilst it is easy and convenient to use the default names (Button1, Button2, etc) or shorthand names (like T1, T2) it can make it hard to follow applicaiton flow. When we post examples we tend to leave the names defaulted because its just an example. You should try and get in the habit of naming things clearly when you make them.
I think whats happening is you are clicking Button2 to fill the form, but if you check your code Button2 is the one that submits the form. SO you submit the form then click Button3 which is trying to populat the form that is no longer there.
Rename your controls and their event handlers and ensure that your code logic follows the path you think it does :)

so yours works fine and the site redirects you to another page saying
Pinging complete!
Bookmark this page and come back to it later to automatically re-ping.
If so do you think that you can upload your project code so i can download it and see if it works then so i can continue using my code?

button one is correct for the code and the page still does not load
but i will sort the code out again

here is the semi updated code it still does not work
i know you said to make them not the default value names
but i have on my design 3 labels saying 1 2 3 next to the correct box
so this should not be problem

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://pingomatic.com/");
            button2.Enabled = false;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            button2.Enabled = true;
        }


        private void button2_Click(object sender, EventArgs e)
        {

            webBrowser1.Document.GetElementById("title").SetAttribute("value", textBox1.Text);
            webBrowser1.Document.GetElementById("blogurl").SetAttribute("value", textBox2.Text);
            HtmlElement button = webBrowser1.Document.GetElementById("checkall");
            if (button != null)
                button.InvokeMember("click");
        }

        private void button3_Click(object sender, EventArgs e)
        {

            HtmlElement elem = webBrowser1.Document.GetElementById("pingform");
            elem.InvokeMember("submit");
        }

       






    }



}

I can post my code, but its the same as you have, i jsut added the controls to a form and pasted it into the event handlers : /
I'd suggest starting a new project. Add the controls and name them correctly. Then create the event handlers and put the code into them and try that. You must have inadvertantly altered something that is stopping the webBrowser from loading.

Can you please post the code you used so i know im not using a weird somehow bad copy :P

without the code you gave me ):
i made this it still does not connect to the site
now it crashes on the form fill back to square one it feels like )::::

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Quickly_Ping
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void Pageload_Click(object sender, EventArgs e)
        {
            webBrowser.Navigate("http://pingomatic.com/");
            Submit.Enabled = false;
        }

        private void autofill_Click(object sender, EventArgs e)
        {

            webBrowser.Document.GetElementById("title").SetAttribute("value", BlogTitle.Text);
            webBrowser.Document.GetElementById("blogurl").SetAttribute("value", BlogUrl.Text);
            HtmlElement button = webBrowser.Document.GetElementById("checkall");
            if (button != null)
                button.InvokeMember("click");
        }

        private void Submit_Click(object sender, EventArgs e)
        {

            HtmlElement elem = webBrowser.Document.GetElementById("pingform");
            elem.InvokeMember("submit");
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Submit.Enabled = true;
        }

       







    }



}

Sure, heres my code, but as i said its the same as yours. Did you make a fresh project?

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void PageLoad_Click(object sender, EventArgs e)
        {
            webBrowser.Navigate("http://pingomatic.com/");
            autofill.Enabled = false;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            autofill.Enabled = true;
        }

        private void autofill_Click(object sender, EventArgs e)
        {
            webBrowser.Document.GetElementById("title").SetAttribute("value", BlogTitle.Text);
            webBrowser.Document.GetElementById("blogurl").SetAttribute("value", BlogUrl.Text);
            HtmlElement button = webBrowser.Document.GetElementById("checkall");
            if (button != null)
                button.InvokeMember("click");

            Submit.Enabled = true;
        }

        private void Submit_Click(object sender, EventArgs e)
        {
            HtmlElement elem = webBrowser.Document.GetElementById("pingform");
            elem.InvokeMember("submit");
            autofill.Enabled = false;
            Submit.Enabled = false;
        }

    }

Does the page load correctly when you click the PageLoad button? If so, put a breakpoint in at the start of the autofill_Click method and check that the webBrowser page contains the elements you are expecting and find out which is causing the null reference exception.

I am running the exact same code in my autofill button and it works seamlessly.

gah!
yeah i did
the page is still not loading why why why?
is there a setting what could be doing this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.