Search code examples
asp.netcustom-controlsservercontrols

getting value from custom control


I have written an ASP.NET server control.

View state works perfectly, but when I'm trying to get a value of a control on my custom control with its public instant method, it brings me an exception that there are not control with that ID.


Solution

  • If you want to get the values from your custom control, you have to register your controls in OnInit event.

    //Register your controls
    protected override void OnInit(EventArgs e) {
            var controlName = (Type)LoadControl("~/path.ascx");
            controlName.ID = "YOU_MUST_SET_AN_ID";
            placeholder.Controls.Add(controlName);
    }
    
    
    //get your controls (add the following in any method you like)
    var controlNameCtrl = (Type)placeholder.FindControl("CONTROLID");
    var propertyValue = controlNameCtrl.PropertyName;