Videos | Podcasts

Changing Style Sheet of Controls Dynamically
AzamSharp
Published Date: 9/10/2005 6:53:04 PM
Views: 3589

Abstract:
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!

 

 

 




Did you like this article?
kick it on DotNetKicks.com Submit
Similar Articles

CSS Sprites Merging Images to Achieve Better Performance

Why Page Event’s not Work:

Caputurig Back Button Event &amp; Force The Page To Load From Server:

Dynamic Graphics in ASP.Net 2.0

Creating Rounded Corners Using Only CSS

Enter Comment/Feedback

 
 
 
 
 

Comments/Feedbacks