FindControl Method not finding control on page

Austin Harmon asked on October 14, 2020 15:39

I am attempting to use a datalist to display some content. In order to get the values I need I have to grab it from a label on the page using the findcontrol method. The issue I'm running into is that findcontrol only searches the top page level it doesn't dig deeper into the page. My question is how can I use kentico syntax to dig down in the tree to get the current level to access my control?

Here is some code I've tried.

In my web part:
Control c = userData.RecFindControl(this.Parent.Parent.Parent, ControlName);
string item = ((System.Web.UI.WebControls.Label)c.Controls[0]).Text;

Here is code in my class:
// Recursively finding the root control in the control tree and checking the first hierarchy level for the searched control
public Control RecFindControl(Control parent, string id)
{
    //Checking if the control can’t be found on the current level
    Control c = parent.FindControl(id);
    if (c == null && parent.Parent != null)
    {
        //The control wasn’t found, we need to search in higher levels
        c = RecFindControl(parent.Parent, id);
    }
    //We found our control and we don’t need to search further
    if (c != null)
    {
        return c;
    }
    // We arrived at the root but we didn’t find anything. We need to travel down the control tree to check all the nodes of the tree
    return RecDownFindControl(parent, id);
}

//Traveling down the control tree and searching for our control
public Control RecDownFindControl(Control parent, string id)
{
    //Checking all the available controls
    foreach (Control item in parent.Controls)
    {
        Control c = item.FindControl(id);
        if (c != null)
        {
            //We found our control on this level
            return c;
        }
        //Traveling further down if nothing was found
        RecDownFindControl(item, id);
    }
    //If there is no such control in any of the branches the method returns the null value
    return null;
}

However this is not working for me. Even if this code isn't correct is there a way to tell on the page level through the UI how many levels down is needed.

Thank you, Austin

Recent Answers


David te Kloese answered on December 10, 2020 09:46

Hi,

did you solve this already?

Probably your code is executed to soon. Did you debug step through the code to see what happened?

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.