2

I want to programmatically click button on a webpage with source like this

<input alt="BusiBtn" class="aButtn" type="submit" value="Search" tabindex="16">

When I do

WebBrowser b = new WebBrowser();
b.Navigate(URL);
while (b.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
b.Document.GetElementByID("BusiBtn").InvokeMember("click");

I get "Object reference not set to an instance of object error".

Can somebody help.

Thanks Rashmi

1
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. Commented Mar 9, 2014 at 12:19

4 Answers 4

2

What you can do in this case simply find all the HtmlElements having input tag. If you need to invoke all the input tags in general, then just invoke click on them. And if you need only the above input element, then filter all the input tags to search for the specific tag with the attribute values like above. Please have a look at the following code:

HtmlElementCollection elems = b.Document.GetElementsByTagName("input");

foreach (HtmlElement elem in elems)
{
    string altStr = elem.GetAttribute("alt");
    string classStr = elem.GetAttribute("class");
    string typeStr = elem.GetAttribute("type");
    string valueStr = elem.GetAttribute("value");
    string tabindexStr = elem.GetAttribute("tabindex");

    if((altStr == "BusiBtn") && (classStr == "aButtn") && (typeStr == "submit") && (valueStr == "Search") && (tabindexStr == "16"))
    {
        elem.InvokeMember("click");
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're using the wrong field.

alt is for alternative text.

You have not actually given that button an id of BusiBtn.

Try:

<input id="BusiBtn" class="aButtn" type="submit" value="Search" tabindex="16">

The clue is in the GetElementByID call. It's not called GetElementByAlt for a reason ;)

2 Comments

That's what the source looks like. How can I invoke the button without the ID?
if the element has no id, then GetElementByID will not work for you. Use another method that is available that can match a known value.
1

add 'name' property to input tag and then use GetElementsByName property

1 Comment

This is not our website. I am crawling somebody's website and want to programmatically download info by clicking the button.
0

You should use the GetElementsByTagName method instead of GetElementById to get all Input-Elements on the page and then cycle through using GetAttribute. An example can be found here http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname(v=vs.110).aspx.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.