Invoke button click programmatically - c#

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

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

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

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

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.

Related

C# Click on HtmlElement With no ID only Class

I am not using selenium nor anything else, i just want to do it on the webbrowser on the windows form application.
I have a windows form application and i want to click on a button with code but there is no ID.
I tried using a lot of different things found on this websites forums, but none of this works.
Have you tried using WebBrowser.GetElementByTagName("div") and then checking each element against attribute type=submit?
Your code should look something like
HtmlElement submit = FindSubmitElement(webBrowser1.Document);
submit?.InvokeMember("submit");
public HtmlElement FindSubmitElement(HtmlDocument document)
{
HtmlElementCollection elems = document.GetElementsByTagName("div"); // since your tag is div
// this will return collection, even in case there is just one div, find the first one, having an attribute 'type' with value 'submit'
foreach (HtmlElement elem in elems)
{
string type = elem.GetAttribute("type");
if (!string.IsNullOrEmpty(type) && type == "submit")
{
return elem; // if div tag with attribute type is found exit and return that html element
}
}
return null; // if no div tags found with an attribute 'type' return null
}
Check more on GetElementsByTagName method on the MSDN docs. Code is taken from there and adjusted to your need.

Programmatically click button in C#

I'm trying to programmatically click a series of buttons on an HTML web page which looks as follows:
<div class="srp-actions blue-button"><a class="primary-action-button label" href="/people/invite?from=profile&key=243930744&firstName=Will&lastName=Yang&authToken=p8Oz&authType=OUT_OF_NETWORK&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_pri_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary" data-li-result-interaction="instant-connect" data-li-success-text="Invite Sent" data-li-connect-href="/people/contacts-search-invite-submit?memIds=243930744&authTokens=p8Oz&authTypes=OUT_OF_NETWORK&from=voltron&firstName=Will&lastName=Yang&isAjax=true&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_invite_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary">Connect</a><div class="secondary-actions-trigger"><button role="button" class="trigger"><span>Secondary Actions</span></button><ul class="menu"><li>Send InMail</li><li>Share</li></ul></div></div>
Here's the current code to find the button element and perform the action:
HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("a");
// First find and click "Connect" buttons
foreach (HtmlElement item in elements)
{
if (item.OuterHtml.Contains("action-button label") &&
!item.OuterHtml.Contains("Message") &&
item.OuterHtml.Contains("OUT_OF_NETWORK"))
{
item.SetAttribute("href", item.GetAttribute("data-li-connect-href"));
item.InvokeMember("Click");
}
}
The code properly find the anchor element, but the InvokeMember method doesn't seem to yield any result, any idea what is wrong?
The tag you are using does not specify exactly which specific tag you need:
x = webBrowser1.Document.GetElementsByTagName("a")
Instead try :
x= webBrowser1.Document.GetElementsById("anchor_id");
x.InvokeMember("click");
Or try using following method to verify whether its the intended tag you're using via attribute.
if (element.GetAttribute(attribute).Equals(attName))

Web browser control to fill <input> field

I'm trying to open a web page in my webbrowser control and change the value of input fields. Works good when I'm doing it like this webBrowser.Document.GetElementById("Email").SetAttribute("value", "example#example.com");
on a page with defined element Ids, but now I've encountered a page where the html/javascript looks something like this:
<input id="${Id}" name="${Id}" type="text" class="text field" value="${Value}" title="${ToolTip}" />
So my question is how do I find this specific input field from the C# code?
Try This
This is a C# coding
HtmlElement Elem = AutomationWebBrowser.Document.GetElementById('<your element ID>');
Elem.SetAttribute("value", '<value to assign in input control>');
Also you can use variables inside the GetElementById and SetAttribute function
You can find element by class name by using the following function,
public static HtmlElement GetHTMLElementByClass(HtmlDocument document, String className)
{
foreach (HtmlElement element in document.All)
{
if (element.GetAttribute("className") == className)
{
return element;
}
}
}

GetElementById without id and name HOW?

I need to click the button "Add" in the post new wordpress form, this button is to add tags to the post , the trouble is that button don't have the value and id propertie. Is just like that
the html for the button
input type="button" class="button tagadd" value="Add" tabindex="3"
my tries
webBrowser1.Document.GetElementById("button tagadd").InvokeMember("click");
webBrowser1.Document.GetElementById("Add").InvokeMember("click");
"GetElementById without id"
:-)
Unless you can change the markup for the button
What you need now is to traverse the entire DOM and look for a button in a known place. I'd suggest adding jquery if not already exist to be able for easier dom manipulation/search.
If you add jquery you could do something like $(".tagadd").click()
You could try doing
webBrowser1.document.getElementsByClassName("tagadd")
EDIT: Here is a script to create the getElementsByClassName function if it's not available http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
There is also this http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname.aspx but I've never used it.
Add an ID. Even if you're dynamically generating the buttons this should be trivial.
If you're using jQuery,
$('.tagadd')
will return a collection of everything with the tagadd class applied. You can further filter this by the other classes (button, etc)
Use this:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\s)" + className + "(?:$|\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass
&& elementClass.indexOf(className) != -1
&& hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
and another
Some browsers provide the method getElementsByClassName() which lets you select by class without using jQuery (which is a bit heavy if this is all you need). I haven't tested this so I'm not sure how widely it's supported.
Did I mention that you should give everything an ID?
use TagName isteed for example
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("class") == "button tagadd")
{
elem.InvokeMember("click");
}
}

c# how to retrieve post data

If I have a textbox txtInfo in a form that I submit via post, if I post back to the page I can read the value entered in the textbox using txtInfo.Text. What if I am posting to a different page? Do I have to parse Request.Form for the control name mutilations (which is what I am doing now) or can I get it from that mess .net passes around as state?
Thanks
Thank you for the answers so far... Sorry I should have been a little more clear. This control is a runat="server" control. This is what I am relegated to now - not very pretty.
foreach (String key in page.Request.Form.AllKeys)
{
String[] controlName = key.Split('$');//remove that horrrible .net naming - thanks Bill.
keyName = controlName[controlName.Length - 1];//get the last value so we always have the name
keyValue = page.Request.Form[key];
if (keyValue != "")
{
switch (keyName)...
You should look into Cross Page Postbacks.
As noted on this page you can easily get access to txtInfo using the following:
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("txtInfo");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
What's wrong with...
string txtInfo = Request.Form["txtInfo"];
if(txtInfo == null) txtInfo = "";
A simple solution would be use a simple <input type="text"> instead of an <asp:TextBox>. Give it a name attribute and then access it via Request.Form.
.aspx file:
<input type="text" name="foo" />
Posted-to code-behind (same page, different page, doesn't matter):
var text = Request.Form["foo"];

Categories

Resources