简体   繁体   中英

Trying to Select the value of a DropDown in a WebBrowser Control (AJAX)

I'm trying to select a value from a second dropdown list which is updated dynamically.

Here is my code for the second dropdown:

HtmlElementCollection select = x.GetElementsByTagName("select");
foreach (HtmlElement el in select)
{
    if (el.Name == "color")
    {
        foreach (HtmlElement ele in el.GetElementsByTagName("option"))
        {
            //MessageBox.Show(ele.InnerHtml);
            if (ele.InnerText == "green")
            {
                ele.Focus();
                ele.SetAttribute("selected", "selected");
                el.InvokeMember("onchange");
                ele.RemoveFocus();
                break;
            }
         }
      }
   }

The code works but only if I use the MessageBox statement. If I comment the MessageBox line, the dropdown option won't be selected.

What event is the MessageBox raising ?

I don't have an explanation for the behavior that you are seeing but in my extensive work with WebBrowser controls in the past I have come across some unexplicable behaviors, too.

Anyway, here are a few things you can try:

  • I assume that you verified by other means that when you don't have a MessageBox statement placed, that the inner part of the if clause gets executed?
  • Just assign the ele.InnerHtml to a string (maybe do something with the string to guarantee that JITing doesn't optimize it away. Accessing InnerHtml might trigger something within the element that causes the event to work.
  • Instead of setting the "selected" attribute and invoking "onchange", try setting ele.selectedIndex of IHTMLSelectElement.
  • Generally, you should not have to invoke "onchange" explicitly. If JavaScript code has subscribed to that event, IE should automatically call that.
  • Is this method being executed on the UI thread? I found that WebBrowser can act weird when you access the DOM from a background thread. If not the UI thread, use Invoke to marshal method execution to the UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM