【问题标题】:Select value in multiselect through c# code通过c#代码在多选中选择值
【发布时间】:2015-07-17 07:21:52
【问题描述】:

伙计们!我必须通过包含 Web 浏览器的 win 表单应用程序中的代码自动设置一些字段值。唯一不起作用的是在多选中设置值。我可以通过代码单击按钮、设置文本框字段等,但多选列表不起作用(无法正确设置值)。首先,这是该元素在页面中的 HTML 代码:

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

我尝试以这种方式首先取消选择所有元素:

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

然后我尝试以这种方式选择(仅一个)所需的元素(值):

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

首先我必须取消选择选定的选项,然后选择我想要的单个选项。如果我仅尝试使用 Replace 方法更改 html,则它不起作用,仅设置 selected 属性也不起作用。当任何值发生变化时(当调用 onchange 函数时 - 我必须在任何地方设置值时调用它)页面中的其他字段也会发生变化,这就是我必须调用“onchange”函数的原因。当代码执行时,所有选项都消失了,多选框为空,我觉得这很奇怪。任何如何解决我的问题的建议将不胜感激。

【问题讨论】:

    标签: c# html winforms webbrowser-control


    【解决方案1】:

    忘记更换业务。

    你需要做的是设置“selectHtmlElemnt的“value”属性(不要乱用任何“optionHtmlElement

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

    【讨论】:

      【解决方案2】:

      你可以使用 jQuery/javascript 来做到这一点

      此示例代码 sn-p 可能会对您有所帮助。

      $("select option").each(function(){
        if ($(this).text() == "B")
          $(this).attr("selected","selected");
      });
      

      【讨论】:

      • 好吧,我的应用程序不是 Web 表单,而是 win 表单,如果您能告诉我如何在 win forms 应用程序中执行 javascript,我将不胜感激。
      • @Aleksandar IT 似乎从您的代码中可以看出您要求使用 Web 表单,对于 Windows 表单,我提供的代码可能对您没有帮助,因为 jQuery 严重依赖 DOM,而 Windows 表单根本不是为它而生。但是如果你仍然有兴趣做一点搜索..点击链接...stackoverflow.com/questions/8356990/…
      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2012-10-05
      • 2016-12-25
      相关资源
      最近更新 更多