Rashmi
Rashmi

Reputation: 121

Invoke button click programmatically

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

Upvotes: 2

Views: 2572

Answers (4)

Wasif Hossain
Wasif Hossain

Reputation: 3960

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

Upvotes: 2

IliaJ
IliaJ

Reputation: 159

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.

Upvotes: 0

James Aster
James Aster

Reputation: 19

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

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38810

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

Upvotes: 1

Related Questions