CSS (Cascading Style Sheets) provides easy maintenance for the look and feel of the website. Sometimes we need to set the style of lot of controls dynamically using style sheet. In this article I will show how you can change the style sheet of the dynamically created label controls.

Introduction:

CSS (Cascading Style Sheets) provides easy maintenance for the look and feel of the website. Sometimes we need to set the style of lot of controls dynamically using style sheet. In this article I will show how you can change the style sheet of the dynamically created label controls.

Changing Style of Dynamically Created Label Controls:

First thing we will do is to create few label controls inside a panel control. Check out the code below. All I am doing is running a simple loop which calls the BuildLabels() method 10 times, creates a new label and pushes it in the Panel control.

private void Page_Load(object sender, System.EventArgs e)

{

// Create 10 Labels

for(int i=1;i<=10;i++)

{

BuildLabels();

}

Panel1.DataBind();

}

private void BuildLabels()

{

Label l = new Label();

l.Text = "See the Color Change";

Panel1.Controls.Add(l);

}

 

I have a DropDownList on the form which allows me to choose a particular style sheet. Once the selection has been made and I press the Button than the Labels are changes according to that style sheet. 

private void Button1_Click(object sender, System.EventArgs e)

{

// I made 10 Labels controls dynamically and put them inside the Panel control

string style = ddlStyle.SelectedItem.Value;

// Go into the Page Control Collection

foreach(Control c in Page.Controls)

{

if(c.HasControls())

{

// Go inside the form element

foreach(Control c2 in c.Controls)

{

// go inside the Panel control

foreach(Control c3 in c2.Controls)

{

// Check if the control is label or not

if(c3.GetType() == new Label().GetType())

{

// Set the CSS class

Label l = (Label) c3;

// Set the Style

l.CssClass = style;

}

}

}

}

}

 

In the above code all I am doing is digging deep into the Page Control hierarchy. I go inside the Page Control where I find the FORM element. After FORM element I found Panel Control and finally inside Panel I found 10 Labels which we generated earlier. Once I found the Label I change the style using CssClass property.

I hope you liked the article, happy coding!