Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically select an item from a drop down in .NET Webbrowser Control

Below is a html script, I grabbed from a website. I wanna select the item programmatically using .NET

<div id="MySite.condition_s-wrp" class="c-wrp-slctbx" style="z-index: 1;">
    <input id="MySite.condition_s-input" type="text" autocomplete="off" readonly="readonly" tabindex="0" class=" c-slctbx-medium" style="width: 268px;">
    <ul class="c-ul-slctbx max_height_300" style="width: 285px; display: none; top: 21px;">
        <li id="MySite.condition_s-option-" class="c-li-slctbx">Please choose</li>
        <li id="MySite.condition_s-option-First" class="c-li-slctbx">First</li>
        <li id="MySite.condition_s-option-Second" class="c-li-slctbx">Second</li>
    </ul>
    <select id="MySite.condition_s" name="attributeMap[MySite.condition_s]" class=" c-slctbx-medium" style="display: none;">
        <option value="">Please choose</option>
        <option value="First">First</option>
        <option value="Second">Second</option>
        </select>
</div>

Please note the following code is not working at all.

webBrowser1.Document.GetElementById("MySite.condition_s").SetAttribute("value", "First");

Any quick help will be highly appreciated.

like image 985
Muhammad Sharjeel Ahsan Avatar asked Mar 07 '13 07:03

Muhammad Sharjeel Ahsan


1 Answers

Finally I figure it out with one of my friends. This little function will do the rest very easily.

Thanks to Farrukh Momin and his time.

    public void SetComboItem(string id, string value) {
        HtmlElement ee = this.webBrowser1.Document.GetElementById(id);
        foreach (HtmlElement item in ee.Children) {
            if (item.OuterHtml.ToLower().IndexOf(value.ToLower()) >= 0) {
                item.SetAttribute("selected", "selected");
                item.InvokeMember("onChange");
            }
            else {
                item.SetAttribute("selected", "");
            }
        }

        ee = this.webBrowser1.Document.GetElementById(id + "-input");
        ee.InnerText = value;
    }

Calling Function

    this.SetComboItem("MySite.condition_s", "First");
like image 177
Muhammad Sharjeel Ahsan Avatar answered Oct 01 '22 21:10

Muhammad Sharjeel Ahsan