get control by clientID

Roy Amir picture Roy Amir · Oct 14, 2010 · Viewed 14k times · Source

i resolve a client id of a Repeater Item control, and i want to use it in other command, how cant i get the control by his client id?

TextBox TB = FindControl...?

Answer

Madeleine picture Madeleine · Oct 14, 2010

Are you trying to find the textbox that resides inside the repeater? If so, you could use the method below which searches based on the ID of the control - you could modify it to check based on the clientID of the control instead.

  public static System.Web.UI.Control FindControlIterative(System.Web.UI.Control root, string id)
    {
        System.Web.UI.Control ctl = root;
        var ctls = new LinkedList<System.Web.UI.Control>();

        while (ctl != null)
        {
            if (ctl.ID == id)
                return ctl;
            foreach (System.Web.UI.Control child in ctl.Controls)
            {
                if (child.ID == id)
                    return child;
                if (child.HasControls())
                    ctls.AddLast(child);
            }
            if (ctls.First != null)
            {
                ctl = ctls.First.Value;
                ctls.Remove(ctl);
            }
            else return null;
        }
        return null;
    }