2

I am trying to match the first word in a drop down list with a given string. What is happening is when I am creating a new drop-down name, it is getting updated by some different name, though the first word remains same.

The code I am using is:

public void DeleteStyleGroup()
    {
        var StyleGroupName = Driver.Instance.FindElement(By.Name("sgroupnbr"));
        StyleGroupName.Click();
        var selectelement = new SelectElement(StyleGroupName);
        selectelement.SelectByText(GrpName);

     }

The drop-down field name here is "sgroupbr"

In my Unit test class, the code I am using is:

 public class DeleteStyleGroup : ibankTest
{
[TestMethod]
public void Delete_Style_Group()
{

StyleGrp.GrpNme("AdrijaTest").DeleteStyleGroup();
}
[TestInitialize]
public void ClassInit()
{
StyleGrp.Goto();
StyleGrp.StyltGroupName("AdrijaTest").Configuration("C3 One Tab").Save();
}
}

So the the group name is a method where it tries to find the drop-down name "AdrijaTest", but it is getting updated with some other name like "AdrijaTest 401".

Can someone please help?

2 Answers 2

1

The easiest solution would probably to just use a css selector instead of looping over every possible candidate. The selector select[name^='sgroupnbr'] will return a select which name starts with (thats the purpose of the ^= operator) sgroupnbr.

That way you should get a value in pretty much constant time, no matter how many selects you have on your page.

0
  1. Write the function to get the first option that matched given string and return full text of that option

    public string GetFirstOptionMatchedGivenString(SelectElement dropdown, string givenString)
    {
        foreach (WebElement option in dropdown.Options)
        {
            if(option.Text.Contains(givenString))
            {
                return option.Text;
            }
        }
    }
    
  2. And modify your code to select option by the returned text

    public void DeleteStyleGroup()
    {
        WebElement StyleGroupName = Driver.Instance.FindElement(By.Name("sgroupnbr"));
        StyleGroupName.Click();
        Select selectelement = new SelectElement(StyleGroupName);
    
        // get first option
        String firstOption= GetFirstOptionMatchedGivenString(selectelement, GrpName);
    
        selectelement.SelectByText(firstOption);
    }
    

I didn't check this function, but it should work. Feel free to get back if it does not work.

1
  • Small addendum: This works well for small dropdowns but if you query a long list of options (for example a country list) you should use the JavaScriptExecutor class and have it return your WebElement to avoid doing a TCP round trip for every single options text value.
    – Daniel
    Commented Apr 23, 2020 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.