How do I programmatically click on a div in a web browser? - c#

I have been trying for a few days now and still have had no success in programmatically clicking on this div. All of the other input fields and buttons are working fine using InvokeMember("click") and RaiseEvent("onclick"), but I am unable to click on the following div:
<div class="pump request"> onclick="$(this).push('kjhzsd94vibjktj584ed01', null, event)" </div>
This div is repeated several times on a page, but I just want to click on the first occurrence.
This is what I have done so far:
HtmlElementCollection c1 = wbc1.document.GetElementsByTagName("div");
foreach (HtmlElement e2 in c1)
{
if (e2.GetAttribute("class").Contains("pump request"))//also this condition is not returning true
{
e2.RaiseEvent("onclick");
}
}
#bleepzter
what if "somecontrol" is a class of the div instead of div's id?
since in my case i have div class "pump request" so (if i write "pump request" as somecontrol in above example) it return me Null in someDiv
<div class="pump request"> onclick="$(this).push('kjhzsd94vibjktj584ed01', null, event)" </div>
#Cameron
yep i did entered the break; but the problem is the if condition never returns true so
HtmlElementCollection c1 = wbc1.document.GetElementsByTagName("div");
foreach (HtmlElement e2 in c1)
{
if (e2.GetAttribute("class").Contains("pump request"))//--> This condition is not returning true
{
e2.RaiseEvent("onclick");
break;
}
}
#Ilya Kogan
yea i just did a watch on e2.GetAttribute("class") and the weird thing happened that being reading the actual div (which i want to click) the value of class was empty :-o

try this one
if (e2.GetAttribute("className").Contains("pump request"))
{
e2.InvokeMember("Click");
}

you can try this piece of code by using a web browser control.
// browser is the web browser control
HtmlElementCollection col = browser.Document.GetElementsByTagName("div");
foreach (HtmlElement helemnt in col)
{
if (helemnt.InnerText !=null && helemnt.InnerText=="something")
{
helemnt.InvokeMember("Click");
break; // break the loop
}
}

It is simple. Here is an example which assumes your browser control is called browser, and the div you are looking for is called somecontrol (i.e. the id of the div is somecontrol):
HtmlElement someDiv = browser.Document.All["somecontrol"];
object someDivElement = someDiv.DomElement;
MethodInfo clickMethod = someDivElement.GetType().GetMethod("click");
clickMethod.Invoke(someDivElement, null);
All this is possible via reflection.

Related

How radio button click if included onclick function?

<asp: label input name="id" value="p" onclick="form.submit();
return false;" type="radio">personal / romance
/label>
I am trying below both code but not getting any solution. Please if anyone have any good solution then it's really good help for me.
webBrowser1.Document.GetElementById("id").SetAttribute("value", "P");
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("label"))
{
if (el.InnerText == ("personal romance"))
{
el.InvokeMember("Click");
}
}
Your code looks okay, but the InnerText of the label is not personal romance
Try it like this:
string searchString = #"personal / romance";
if(el.InnerText.Equals(searchString)
{
el.InvokeMember("click");
}
Check when expect this element if the correct tag name is label. I can tell you for sure that this is not asp:label. You can check with Inspect Elements in Chrome, if the tag name is different use correct one when you are taking webBrowser1.Document.GetElementsByTagName(correct tag)

Post to facebook group with C# code

I am working on a windows application where I embedded webbroswercontrol. I am trying to post sample message to a open facebook group. I am unable to change value of a textbox with c#. When ever I automate click it says textbox value is null. What would be the fix?
<input type="hidden" autocomplete="off" class="mentionsHidden"
name="xhpc_message" value="lklklkl">
HtmlElement textBox = this.FindControlByName("xhpc_message",
this.webBrowser.Document.All);
//Click Code
var elements = webBrowser.Document.GetElementsByTagName("button");
foreach (HtmlElement element in elements)
{
// If there's more than one button, you can check the
//element.InnerHTML to see if it's the one you want
if (element.InnerText.Contains("Post"))
{
if (textBox.InnerText.Trim() == "Write something...")
{
textBox.Focus();
textBox.GetAttribute("value").Equals("Test Message");
IHTMLElement nativeElement = element.DomElement as IHTMLElement;
nativeElement.click();
break;
}
}
}
1) I suggest you to ensure, that textbox is null, not the textBox.InnerText. Usually inner text for elements is null, so its better to check the "placeholder" attribute and update the code with:
// if (textBox.InnerText.Trim() == "Write something...")
if (textBox.GetAttribute("placeholder") == "Write something...")
2) This code doesn't set the value. It gets the value and compares to "Test message".
textBox.GetAttribute("value").Equals("Test Message");
Just use SetValue instead.
textBox.SetAttribute("value", "Test message");
3) Ensure, that all operations are made after page is loaded.
public SomeFormName()
{
...
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs args)
{
// put your code here
}
4) Not sure, how the FindControlByName is working, so check a simple LINQ query to ensure that textbox is found.
var textbox = webBrowser.Document.All.OfType<HtmlElement>()
.Where(item => item.Name == "xhpc_message")
.FirstOrDefault()
;
Use the code below after the Document complete event has been fired completely in a separate function, after commenting your code.The URL in the webbrowser should be holding the Group Page on which the post is to happen.
private void AfteDocumentLoads()
{
HtmlElementCollection textBox = webBrowser.Document.GetElementsByTagName("textarea").GetElementsByName("xhpc_message");
HtmlElementCollection button = webBrowser.Document.GetElementsByTagName("button");
foreach (HtmlElement element in textBox)
{
foreach (HtmlElement btnelement in button)
{
if (btnelement.InnerText == "Post")
{
element.Focus();
element.InnerText = txtPortalUserId.Text.ToString();
btnelement.InvokeMember("Click");
}
}
}
}
I was also stuck as it was not posting earlier because I was using WebBrowser class to get current WebBrowser. Result was that the text was inputted to the Group as a 'dim' Comment. Even if I clicked manually on FB page it would say "This status update appears to be blank. Please write something or attach a link or photo to update your status."
I used the page's webbrowser & it worked cos' it came in proper manner on the page. Also little bit of changes are there in the LOCs

Calling div from code behind c#

<blink>in condition i want to call div from html , which contains background image only, and I need to call it on just few pages
with same metadata. So how will i call that div, i tried few ways but
nothing helped me.
if (cMeta != null && cMeta.Name == "background")
{
if (cMeta.Text == "Yes")
{
Display(Div)
}
}
Thanks
Set runat="server" to div markup.
<div id="myDiv" runat="server"></div>
Now in code behind you can access the myDiv
private void DisplayDiv(bool isShow)
{
myDiv.Visible = isShow;
}
Now when you want to show it then just call this function with true value
DisplayDiv(true);
otherwise just call it with false ,if you don't want to show it.

How can I make elements visible in C# Webbrowser?

HTML code (example):
<div class="clsA"><div class="clsA1">TEXT</div></div> <div class="clsB"></div>
I want make DIV which have class-attribute is clsA and their child-elements visible.
(both clsA and clsA1 appear).
I try
foreach (HtmlElement pageElement in webBrowser1.Document.All)
{
if (pageElement.GetAttribute("className").ToLower() != "clsa")
pageElement.Style = "display:none";
}
but everything disappear.
Thanks
The uppercase A in "clsA" will never match a to lower string, so you will set every item on the page to display:none.

Creating and finding dynamic controls on a page

There is a problem to find a dynamic control on a page. The dynamic control is created every time when a user press a button. The button calls the following JavaScript function and create a new components.
<script type="text/javascript">
var uploadCount = 1;
function addFileInput(fName) {
var only_file_name = fName.replace(/^.*[\\\/]/, '');
var $div = $('<div />', {runat: 'server'});
var $cbox = $('<input />', { type: 'checkbox', id: 'attachement' + uploadCount, value: fName, checked: "true", runat: 'server'}).addClass;
var $label = $('<label />', { 'for': 'attachement' + uploadCount, text: only_file_name });
$div.append($cbox);
$div.append($label);
$('#newAttachment').append($div);
$("#uploadCountValue").prop("value", uploadCount);
uploadCount++;
}
</script>
newAttachment is DIV section on the page.
<div id="newAttachement" runat="server" />
The DIV section is situated inside section. The problem is when a user presses the button on the form I can't find the dynamic created components. The following code shows how I try to find the components:
for (int i = 1; i <= Convert.ToInt32(uploadCountValue.Value); i++)
{
if (RecursiveFind(newAttachement, "attachement" + i) != null)
{
... to do something
}
}
public Control RecursiveFind(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.ID == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = RecursiveFind(ChildCntl, NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
I have detected that Controls count value is always zero in spite of there are dynamic components there.
I would be happy to get any help from us. Thanks.
to find the controls created in the client-end you can't search them in the Page.Controls collection instead try to look for them in the Request.Form[] array
you are creating the dynamic controls in javascript? i.e. you are creating html elements in javascript. It won't matter even if you put a runat="server" attribute in there, because it is still at the client-end. That would not be a part of the viewstate bag, so not populated in the controls collection.
you need to change your logic. create dynamic control in code-behind on button postback.

Categories