简体   繁体   English

c#在WebBrowser控件的多个下拉列表中选择单个项目

[英]c# Select Single Item in Multiple Drop Down List in WebBrowser Control

I've been searching for a solution for this problem, but have yet to find one that works. 我一直在寻找解决此问题的方法,但尚未找到可行的方法。 I have a webBrowser control. 我有一个webBrowser控件。 There is a multiple drop down list that is structured like this: 有一个多重下拉列表,其结构如下:

<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab" SELECTED>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi" SELECTED>Audi</option>
</select>

<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

There are already some options selected. 已经选择了一些选项。 I need to select one other option, such as "Volvo" The typical was to do this would be to hold the ctrl key and right click on the option. 我需要选择其他选项,例如“ Volvo”。通常的做法是按住ctrl键并右键单击该选项。 I was looking at the sendKeys class, but I'm not entirely sure I'm doing it right. 我当时在看sendKeys类,但是我不完全确定自己做对了。 Here is what I have tried: 这是我尝试过的:

foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("option"))
{
    if (item.InnerText == "Volvo")
    {
        item.Focus();
        SendKeys.Send("^(+)");//sends ctrl-space
    }
}

It doesn't seem to give the item focus, so I'm not sure if the SendKeys is working or not. 它似乎没有给项目重点,所以我不确定SendKeys是否正常工作。

I also tried this : 我也尝试过这个:

foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("option"))
{
    if (item.InnerText == "Volvo")
    {
        item.SetAttribute("SELECTED", "");
    }
}

...but this does not seem to work either. ...但这似乎也不起作用。
Any help is appreciated 任何帮助表示赞赏

Well, I'm embarrassed to say that the answer was surprisingly simple... 好吧,我不好意思说答案非常简单...

Apparently the SetAttribute method does not take an empty string as a second argument. 显然,SetAttribute方法不会将空字符串作为第二个参数。 This is the solution that worked: 这是有效的解决方案:

foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("option"))
{
    if (item.InnerText == "Volvo")
    {
        item.SetAttribute("SELECTED", "SELECTED");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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