Search code examples
c#watin

WatiN: Unable to click an Element twice - "Could not find element" error


I am running into an issue where I need to click on an element twice. The first time the element is clicked it expands a tree on the page, the second time closes the tree. There is no issue when clicking the element the first time.

Here is the part of the HTML code I am working with: (The element I am clicking is the 'a' tag.)

<div id="uasMainForm:uasTabs:0:agencyTree-d-rt-c" name="c">
    <div title="" class="iceTreeRow" id="uasMainForm:uasTabs:0:agencyTree-d-4" name="nd">
        <a id="uasMainForm:uasTabs:0:agencyTree:4" onclick="document.forms['uasMainForm']['uasMainForm:uasMainForm:uasTabs:0:agencyTree_idtn'].value='4';iceSubmitPartial( document.forms['uasMainForm'], this,event); return false;" onblur="setFocus('');" href="javascript:;">

The weird thing is, if I run the second click immediately after running the first it closes the tree perfectly, but if I break it up with a MessageBox or some other code it throws an error when trying to perform the second click.

Here is code that works:

agency = ie.ElementOfType<Div>(Find.ByText(agencyName));
agencyTab = agency.ElementWithTag("a", Find.ByIndex(0));
agencyTab.Click();

//MessageBox.Show("Hey!");
agencyTab.Click();

Here is the code that does not work:

agency = ie.ElementOfType<Div>(Find.ByText(agencyName));
agencyTab = agency.ElementWithTag("a", Find.ByIndex(0));
agencyTab.Click();

MessageBox.Show("Hey!");
agencyTab.Click();

The above code throws the error: Could not find A element tag matching criteria: Index = 0

I have also tried Find.ById instead of ByIndex with the same result. Can anyone shed some light on what could be causing this error when breaking up the two click events, but not when the click events happen back to back?


Solution

  • I'm still not sure why this issue was occuring but I found a way around it. First I save the Id of the containing Div right before I do the first click:

    var agency = ie.ElementOfType<Div>(Find.ByText(agencyName));
    
    //Set current agency Id
    currentAgency = agency.Id;
    
    var agencyTab = agency.ElementWithTag("a", Find.ByIndex(0));
    agencyTab.Click();
    

    Then, when I want to perform the second click, I use the Id I saved earlier to find the containing Div again:

    //Close old agency's tree
    var agency2 = ie.ElementOfType<Div>(Find.ById(currentAgency));
    var agencyTab2 = agency2.ElementWithTag("a", Find.ByIndex(0));
    agencyTab2.Click();