Set html Select option using c#

c# html html-agility-pack

Question

Okay, so this seems like an easy thing to do but I cannot find how to do it. I have used the htmlagility pack to parse the web page and it works great. Now, the issue is that the following.

<td width="45%" class="TextBold" nowrap>
<select name="ctl00$BodyContent$ddlChooseView" onchange="if (this.selectedIndex > 0
{pageTracker._trackEvent('webpage tracker','complete report',this.options
[this.selectedIndex].text);}
ShowProcessing(this);setTimeout('__doPostBack(\'ctl00$BodyContent$ddlChooseView\',\'\')', 
    0)" id="ctl00_BodyContent_ddlChooseView" class="TextBold">
        <option selected="selected" value=""> -- Select a view -- </option>
        <option value="H">Option1</option>
        <option value="R">Option2</option>
        <option value="N">Option3</option>
        <option value="NA">Option4</option>
        <option value="RN">Option5</option>
        <option value="QP">Option6</option>

</select>
</td>

I apologize if this did not format correctly. And I want to select one of the options in the html select object. To trigger a new display on the page and then parse that "new" webpage. Can htmlagilitypack do this? If not, what can I do to select one of the options?

Popular Answer

This code may be useful to you It contains the basic details.

<code>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

//Need to add these two libarary
//For that u need to have WebDriver.dll and WebDriver.Support.dll 
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace Test
{
class Program
{
static void Main(string[] args)
{
//Intializing the webdriver. 
//Note i m using firefox driver, others can also be used.
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
//Navigating to the given page.
driver.Navigate().GoToUrl("url of the page you want to get the option from");
//Finding the element. If element not present it throws exception so do remember to handle it.
var element = driver.FindElement(By.Id("ctl00_BodyContent_ddlChooseView"));
//No intializing the select element option.
SelectElement selectElem = new SelectElement(element);
selectElem.SelectByValue("H"); 
//or i can select option using text that is
selectElem.SelectByText("Option1"); 
}

}
}
</code>

Sorry for the indentation.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why