1

guys! I have to set some fields values automatically through code in my win forms application, which contains a web browser. The only thing not working is setting value in multiselect. I can click buttons through code, set textbox fields and etc, but the multiselect list do not work (can't set value properly). First of all, this is the HTML code in the page for this element:

<select size="10" name="someName" multiple="multiple" onchange="javascript:setTimeout('someFunc')" id="elementId" showconfirmedonly="true" showextraitems="true">
    <option selected="selected" value="1">First opt</option>
    <option value="2">Second opt</option>
    <option value="3">Third opt</option>
    <...other options...>
</select>

I try to deselect all the elements first this way:

webBrowser.Document.GetElementById(elementId).InnerHtml =
webBrowser.Document.GetElementById(elementId).InnerHtml.Replace(
"<option selected=\"selected\"", "<option");

and then I try to select (only one) the desired element(value) this way:

webBrowser.Document.GetElementById(elementIWantToSelectId).Focus();
element.SetAttribute("selected", "selected");
webBrowser.Document.GetElementById(elementIWantToSelectId).InvokeMember("onchange");

First i must deselect the selected options, and select my desired single option. If I try only to change the html with the Replace method , it doesn't work, neither with only setting selected attribute. The other fields in the page change when any value changes (when onchange func is called - I must invoke it when setting value anywhere) and that's why I have to invoke 'onchange' function. When the code executes, all the options disappear and the multiselect box is empty, which I find really strange. Any suggestions how to solve my problem would be appreciated.

Aleksandar
  • 11
  • 1

2 Answers2

-1

You can do this using jQuery/ javascript

This sample code snippet might help you.

$("select option").each(function(){
  if ($(this).text() == "B")
    $(this).attr("selected","selected");
});
Mayur A Muley
  • 51
  • 1
  • 12
  • Well, my app is not web forms,but win forms and I would be thankful if you tell me how to execute javascript in win forms app if that's what you mean. – Aleksandar Jul 17 '15 at 14:10
  • @Aleksandar IT seems from your code that you were asking for web forms, In the case of Windows Forms, the code I gave might not help you as jQuery heavily depends on DOM and windows forms are simply not made for it. But if you are still Interested doing a bit search.. Follow the link ... http://stackoverflow.com/questions/8356990/javascript-jquery-in-windows-applications – Mayur A Muley Jul 19 '15 at 14:35
-1

Forget the replace business.

What you need to do is set the "value" attribute of the "select" HtmlElemnt (don't mess with any of the "option" HtmlElement)

webBrowser.Document.GetElementById(elementId).SetAttribute("value", "1");

banging
  • 2,540
  • 1
  • 22
  • 26