简体   繁体   中英

Find dynamically created control

I'm dynamically creating an HTML table filled with devex radio list controls and adding it to the page.

//Create the radio list
ASPxRadioButtonList radButt = new ASPxRadioButtonList();
radButt.ID = "audit-" + audType;

tableCell2.Controls.Add(radButt);
tableRow.Cells.Add(tableCell2);
auditTable.Rows.Add(tableRow);

This all works fine.
Now, inside of a callback, I want to grab that radio list and get its setting ... so I am trying this but keep getting NULL.

ASPxRadioButtonList audRad = (ASPxRadioButtonList)Page.FindControl("audit-" + audType);

What I am missing here?

The problem is that the Page.FindControl method doesn't search all controls on the page. It only searches the top layer of controls. You have to search through all controls on the page using Page.FindControl and Control.FindControl , probably recursively.

Another point, do you mean to find the radiobutton in the postback, or in the same request? If you mean in the postback, than you have to regenerate the control in the postback as well, just like Aniket mentioned.

According to Maarten's answer, here is a recursive FindControl solution directly picked from our Master's blog :

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM