Search code examples
c#asp.netskin

Cannot change SkinID property dynamically


I get this error when I try to have my C# class change the skin of an asp control:

The 'SkinId' property can only be set in or before the Page_PreInit event for static controls. For dynamic controls, set the property before adding it to the Controls collection.

My goal is to provide a panel, call it ID="response", on every page, and then dynamically change it's CSS class from Error to Success, or Success to Error (so it's red or green). And also I make it visible = true, when a response is created.

Apparently, I am forced to use CssClass attribute, which is the only way this will work.

As a side-off-topic note: In PHP, you would not have a problem of using different "pre-init" "post-init" etc. A completely unnecessary process. You would simply change the html before you send it back to the user. I'm a bit confused why ASP.NET decides to overcomplicate everything. It's a bit silly for me to take time to learn all these different complicated processes to simply display a webpage. It takes time to learn all the quirks written in difficult-to-read ASP life-cycle documents on microsoft. Not to insult any microsoft people, but it's just not practical.


Solution

  • If it is a static control, that is you are defining the Panel in your .aspx page, then the only place to change the SkinId is in the PreInit method e.g.:

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        String panelSkin = ViewState("panelSkin").toString();
        panel1.SkinId = panelSkin;
    }
    

    Of Course, the PreInit method is only called when the Page is being first Initialized -- not on a PostBack.

    You could save the skinId you wanted to use to the ViewState and then call a Response.Redirect("myPage.aspx")... and as seen above grab the skinId string from the ViewState and set the Panel skinId accordingly.

    Alternatively, rather than using a Panel try using an UpdatePanel from the .Net Ajax library. Clicking a button in the UpdatePanel (provided it's setup to Trigger an ASyncPostBack) will run the OnPreInit method.

    That said, provided you are changing the background, going with the CssClass property would be the most efficient way to do this.