Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Before software can be reusable it first has to be usable. -- Ralph Johnson

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:06:19 PM CT Jan 09, 2007
Posted:05:15 PM CT Jan 09, 2007

C# StyleHelper Class

A C# class to convert between a Style object, style string or CssStyleCollection

Author: Steve Lautenschlager

SnippetC#ToolsCSSGraphics/DesignWeb

 Summary

As far as I can tell, .NET (as of version 1.1) does not provide an easy way to convert a Style object into a style string or CssStyleCollection. There are situations, especially when applying styles to HtmlControls, where this functionality is needed.

I have written a simple method to do the conversion. It uses the brute force approach, but it works. If there is a more elegant (tested) solution, I'd appreciate hearing about it.

Implement the following method in the code behind file of an ASP.NET page with a Label (lblOutput) and an HTML Table control (htmlTable) with the runat=server attribute:

Example: How to use the StyleHelper Class

private void TestStyleHelper()
{
   // create the style object
   Style style1 = new Style();
   style1.BackColor = Color.Tan;
   style1.ForeColor = Color.DarkBlue;
   style1.BorderWidth = new Unit(2.0, UnitType.Pixel);
   style1.BorderColor = Color.SkyBlue;
   style1.Font.Bold = true;
   style1.Font.Name = "Verdana";
   
   // instantiate the style helper
   StyleHelper helper = new StyleHelper();

   // generate the style string
   lblOutput.Text = helper.StyleToString(style1);

   // apply to CssStyleCollection
   helper.StyleToCollection(style1, htmlTable.Style);

}
If you run the previous method you'll get something similar to the following output:

Example: Output

<!-- The string form of the Style object -->

background-color:#D2B48C;color:#00008B;border:#87CEEB 2px solid;
font-weight:Bold;font-family:Verdana, Verdana;

<!-- htmlTable appearance: Not shown here. -->
Here's the class:

The C# StyleHelper Class:

namespace Cambia.Web.CoreLib
{

   using System;
   using System.Collections;
   using System.Drawing;
   using System.Web.UI;
   using System.Text;
   using System.Web.UI.WebControls;

   /// <summary>
   /// StyleHelper.  Assists in converting a Style object to a text string 
   /// or a CssStyleCollection.
   /// </summary>
   public class StyleHelper
   {
      static char[] hexDigits = 
         {'0', '1', '2', '3', '4', '5', '6', '7', 
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

      public StyleHelper()
      {
      }
	
      #region -- Methods --
      public string StyleToString(Style s) 
      {
         StringBuilder sb = new StringBuilder();

         if (s.BackColor != Color.Empty)
            sb.Append("background-color:" 
               + ColorToHexString(s.BackColor) + ";");
         if (s.ForeColor != Color.Empty)
            sb.Append("color:" 
               + ColorToHexString(s.ForeColor) + ";");

         #region -- Border --
         string color = "black";
         string width = "";
         string style = "solid";
         if (s.BorderColor != Color.Empty)
            color = ColorToHexString(s.BorderColor);
         if (s.BorderStyle != BorderStyle.NotSet)
            style = s.BorderStyle.ToString();
         if (s.BorderWidth != Unit.Empty)
            width = s.BorderWidth.ToString();
         if (color != "" && width != "" && style != "")
            sb.Append("border:" + color + " " + width + " " + style + ";");
         #endregion

         #region -- Font --

         #region -- Font General --
         if (s.Font.Size != FontUnit.Empty)
            sb.Append("font-size:" + s.Font.Size.ToString()+ ";");
         if (s.Font.Bold == true)
            sb.Append("font-weight:Bold;");
         if (s.Font.Italic == true)
            sb.Append("font-style:Italic;");
         #endregion

         #region -- Font Names --
         ArrayList fontList = new ArrayList();
         if (s.Font.Name.Length != 0)
            fontList.Add(s.Font.Name);
         foreach (string f in s.Font.Names)
            fontList.Add(f);
         if (fontList.Count > 0)
         {
            string fontString = "";
            for (int i=0; i<fontList.Count; i++)
            {
            if (i==0)
               fontString = (string)fontList[i];
            else
               fontString += ", " + fontList[i];
            }
            sb.Append("font-family:" + fontString + ";");
         }
         #endregion

         #region - Text Decoration --
         ArrayList decorList = new ArrayList();
         if (s.Font.Underline == true)
            decorList.Add("underline");
         if (s.Font.Overline == true)
            decorList.Add("overline");
         if (s.Font.Strikeout == true)
            decorList.Add("line-through");
         if (decorList.Count > 0)
         {
            string strDecor = "";
            for (int i=0; i<decorList.Count; i++)
            {
               if (i==0)
                  strDecor = (string)decorList[i];
               else
                  strDecor += ", " + decorList[i];
            }
            sb.Append("text-decoration:" + strDecor + ";");
         }
         #endregion

         #endregion

         #region -- Height and Width --
         if (!s.Height.IsEmpty)
            sb.Append("height:" + s.Height.ToString()+ ";");
         if (!s.Width.IsEmpty)
            sb.Append("width:" + s.Width.ToString()+ ";");
         #endregion

         return sb.ToString(); 

      }
      public void StyleToCollection(Style source, 
         CssStyleCollection destination) 
      { 
         string strStyle = StyleToString(source);
         string[] styles = strStyle.Split(new char[] {';'});
         CssStyleCollection c = destination;
         char[] colonSplit = new char[] {':'};
         foreach (string style in styles)
         {
            string[] elements = style.Split(colonSplit);
            if (elements.Length == 2)
               c.Add(elements[0], elements[1]);
         }

      }

      public string ColorToHexString(Color color) 
      {
         byte[] bytes = new byte[3];
         bytes[0] = color.R;
         bytes[1] = color.G;
         bytes[2] = color.B;
         char[] chars = new char[bytes.Length * 2];
         for (int i = 0; i < bytes.Length; i++) 
         {
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
         }
         return "#" + new string(chars);
      }
      #endregion

   }
}

Add New Comment
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com