Q:

Partial Match Select an element in dropdown c#

I have page with lots of dropdowns and I seem to have a problem in writing something generic rather than hardcoding the full path.
The idea is to locate the country dropdown and selecting an item from the dropdown
THIS WORKS
 public MyPage WithCountry(string countryValue)
 {
    driver
    .FindElement(By.CssSelector("#ctl00_MainContentPlaceholder_ApplicantDetails1_Panel_ctl00_ctl03_CountryList > span.ui-selectmenu-text"))
    .Click();

    driver.FindElement(By.Id("ui-id-162")).Click();
    return this;
}

This does not work
 public MyPage WithCountry(string countryValue)
 {   
    var element=driver.FindElement(By.CssSelector( "[Id$=ctl03_CountryList]");  
    element(By.CssSelector("# > span.ui-selectmenu-text")).Click();  //NOT SURE ABOUT THIS GIVES ME ERROR.
    driver.FindElement(By.Name(countryValue)).Click();
    return this;
}

html
    <ul id="ctl00_MainContentPlaceholder_ucApplicantDetails1_ApplicantPanel_ctl00_ctl03_CountryList" class="form-columns">
    <li class="large-4 columns">
            <label for="ctl00_MainContentPlaceholder_ucApplicantDetails1_ApplicantPanel_ctl00_ctl03CountryListList" id="ctl00_MainContentPlaceholder_ucApplicantDetails1_ApplicantPanel_ctl00_ctl03_CountryListLblFor">CountryList&nbsp;
                <span class="req">*</span>
            </label>
    </li>
    <li class="hidden">
            <span id="ctl00_MainContentPlaceholder_ucApplicantDetails1_ApplicantPanel_ctl00_ctl03_CountryListReqVal" style="color:Red;display:none;"></span>
    </li>
    <li class="large-12 columns">
        <select name="ctl00$MainContentPlaceholder$ucApplicantDetails1$ApplicantPanel$ctl00$ctl03$CountryList" id="ctl00_MainContentPlaceholder_ucApplicantDetails1_ApplicantPanel_ctl00_ctl03_CountryList" class="xxx">
            <option selected="selected" value=""></option>
            <option value="Spain">Spain</option>

Can anybody give any suggestions how I should code this method so that an element in the drop down is selected,by finding the element by partial match

A:

Why don't you just use the built-in SelectElement class?
For example I created some extension wrapper methods for it like:
public static void SelectElementByName(this IWebElement selectDropDown, string valueToSelect)
{
    var selectElement = new SelectElement(selectDropDown);
    if (selectElement.SelectedOption.Text == valueToSelect)
    {
        return;
    }
    selectElement.SelectByText(valueToSelect);
}

Usage:
var countrySelectElement = driver.FindElement(By.CssSelector("css_selector_here"));
countrySelectElement.SelectElementByName("Spain");

Then, also using SelectElement class you could get your currently selected element, all the options from the drop-down, etc.
Have a look at the github repo for this: SelectElement

