moonblade
moonblade

Reputation: 287

How do I style a dynamically added control?

In the PreInit event(Have also tried Load event), I am dynamically adding custom user controls at runtime based on conditions in the back end. My problem is that the user control added to the page does not take on the theme the site is currently set to, and is using the default styles for all the controls within it.

How do I go about fixing this? I'm having a hard time finding anything particularly relevant using google.

Upvotes: 0

Views: 4177

Answers (3)

Chris Porter
Chris Porter

Reputation: 3687

Try to divorce your ASP.NET controls from their styling as much as you can. Using CSS classes will allow you to do this easily. You didn't post code samples so I can only guess what your custom controls look like. They likely have some form of container like a div. Determine which layer will handle you CSS class structure, add an asp:Literal to that layer of the markup, then expose the Text property of the Literal as a public property of the control. At runtime when you create and add the control to the Controls collection, you can assign the proper class name for the scenario.

It would look something like this:

<div class="<asp:Literal ID="uxCssClassLiteral" runat="server" />">
    <p>My content goes here</p>
</div>

From code behind

public class MyControlType
{
    public string CssClass 
    {
        get { return this.uxCssClassLiteral.Text; }
        set { this.uxCssClassLiteral.Text = value; }
    }
}

The page would handle the control like this:

public class MyPage 
{
    protected void Page_Load(Object sender, EventArgs e)
    {
        MyControlType controlA = new MyControlType();
        if (condition1 == true)
        {
            controlA.CssClass = "class-name-for-condition-1";
        }
        else 
        {
            controlA.CssClass = "class-name-for-other-condition";
        }
        this.Controls.Add(controlA);
    }
}

Upvotes: 0

moonblade
moonblade

Reputation: 287

Figured it out. My site saves the current theme into a session variable on the initial load. After I have dynamically added my controls to the page, I use the session variable to re-apply my theme. My dynamically added controls then take on the appropriate theme.

Upvotes: 0

boruchsiper
boruchsiper

Reputation: 2038

bunch of ways to do that.

MyControl.Attributes.Add("class", "myclass")
MyControl.Style.Add("background-color", "red")
MyControl.Attributes("bgcolor") = "lightblue"

Upvotes: 2

Related Questions