July 11, 2009

Get Styles from Web Controls

In this example, I will show how to retrieve all the styles and its values from code-behind of an asp.net page. To do so, I will create a page with a div control with some styles. Here is the code for the page,

    <form id="form1" runat="server">
    <div style="color:Red; border:solid 1px red;" runat="server" id="div1">

It's a very simple page with one html control with color and border styles. From the code-behind, I will identify the individual style attribute, that is, color and border and find the assciated values.

Here is the code-behind,

    HtmlGenericControl hc = (HtmlGenericControl)Page.FindControl("div1");//get the div control
    IEnumerator keys = hc.Style.Keys.GetEnumerator();

    while (keys.MoveNext())
    string key = (string)keys.Current;//getting current key
    Response.Write("style: " + key + " value: " + hc.Style[key]);

Here, at first, I am finding the div control using FindControl method and casting it as HtmlGenericControl. Then, creating a iEnumerator collection and assigning it to the styles of the control. Then, looping the collection and getting each value.


Reference: Shahed Kazi at AspNetify.com