Code As follows:
Copy code The Code is as follows: Panel spnbuttons = new Panel ();
Button BTN = new button ();
BTN. ID = "btn1 ";
Spnbuttons. Controls. Add (BTN );
// Output True, indicating that the control is not found
Response. Write (spnbuttons. findcontrol (BTN. ID) = NULL );
The following code can be used:Copy codeThe Code is as follows: Panel spnbuttons = new Panel ();
Page. Controls. Add (spnbuttons); // Add the panel to the page after it is created.
Button BTN = new button ();
BTN. ID = "btn1 ";
Spnbuttons. Controls. Add (BTN );
// Output false, indicating that the control is found
Response. Write (spnbuttons. findcontrol (BTN. ID) = NULL );
You can also use repeater:Copy codeThe Code is as follows: repeater spnbuttons = new repeater ();
Button BTN = new button ();
BTN. ID = "btn1 ";
Spnbuttons. Controls. Add (BTN );
// Output false, indicating that the control is found
Response. Write (spnbuttons. findcontrol (BTN. ID) = NULL );
After checking that panel inherits from webcontrol, webcontrol defines:
Public class webcontrol: control, iattributeaccessor
{}
Repeater is defined:
Public class repeater: control, inamingcontainer
{}
Is it because repeater implements inamingcontainer?
I have customized a class, inherited from panel, and implemented inamingcontainer. Now I can find the control:Copy codeThe Code is as follows: public partial class webform1: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
Mypanel spnbuttons = new mypanel ();
Button BTN = new button ();
BTN. ID = "btn1 ";
Spnbuttons. Controls. Add (BTN );
Response. Write (spnbuttons. findcontrol (BTN. ID) = NULL );
}
}
Public class mypanel: panel, inamingcontainer
{
Public mypanel (): Base ()
{
}
}
In ASP. NET, placeholder, panel, and other controls do not implement inamingcontainer, resulting in invalid findcontrol.
If you add these controls to the parent control that implements inamingcontainer, or use a subclass to implement inamingcontainer, you can make findcontrol effective.