c# - Set Properties of User Control on Event Using FindControl -


i have user control dynamically loaded in the page load:

protected void page_load(object sender, eventargs e) {     mycontrol ctl = (mycontrol)loadcontrol(controlpath);     ctl.id = "mycontrol";     this.mycontrolplaceholder.controls.add(ctl); } 

front end of page:

<asp:placeholder runat="server" id="mycontrolplaceholder"></asp:placeholder> 

i have click event on page initiates , postback , calls method i'm trying find control , set properties:

        mycontrol ctl = (mycontrol)findcontrol("mycontrol");         if (ctl != null){             ctl.myproperty = true;             response.write("success");         }         else             response.write("fail"); 

this writing fail after postback, seems i'm doing incorrectly in finding control. best way this?

edit:

i switched mycontrol ctl = (mycontrol)this.mycontrolplaceholder.findcontrol("mycontrol"); 

this made finding control, however, when control loads after postback, appears though property not set.

you have use recursive findcontrol implementation because findcontrol find direct childs. control inserted in naming container @ lower level. generic findcontrolrecurisve msdn:

private control findcontrolrecursive(control rootcontrol, string controlid) {     if (rootcontrol.id == controlid) return rootcontrol;      foreach (control controltosearch in rootcontrol.controls)     {         control controltoreturn =              findcontrolrecursive(controltosearch, controlid);         if (controltoreturn != null) return controltoreturn;     }     return null; } 

from msdn

or, if have 1 specific conatiner in sample:

mycontrol ctl =  this.mycontrolplaceholder.findcontrol("mycontrol");  if (ctl != null){             ctl.myproperty = true;             response.write("success");         }         else             response.write("fail"); 

viewstate enable control

public class mycontrol:control {    public bool myproperty    {                {            return viewstate["my"] != null? (bool) viewstate["my"]: false;         }        set         {            viewstate["my"]  = value;        }    } } 

Comments