Brendan Tompkins [MVP]

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
The CssStyleCollection

Last week I pointed out that you can use the CopyFrom() to copy font and control styles applied to a WebControl to it's contained controls.   If you missed it, you can use the Font.CopyFrom and ControlStyle.CopyFrom to achieve this.  But what if you don't have the CopyFrom method at your disposal?  This happens with controls in the System.Web.UI.HtmlControls namespace, for example.  Well, you can always use the Style property instead. This is an object of type System.Web.UI.CssStyleCollection.  With a little bit of help, you can use it to pass styles around from control to control.   The static helper methods CopyStyles and GetStyleString can be used to do this.

System.Web.UI.HtmlControls.HtmlButton btn = new System.Web.UI.HtmlControls.HtmlButton();
string style = GetStyleString(this.Style, false
);
CopyStyles(style, btn.Style);

public static void CopyStyles(string sourceStyle, System.Web.UI.CssStyleCollection destinationStyle)
{
  string [] keyvals = sourceStyle.Split(new char
[1] {';'});
  foreach(string keyvalpair in
keyvals)
  {
     keyvalpair.Trim();
     string [] keyVal = keyvalpair.Split(new char
[1] {':'}, 2);
     if
(keyVal.Length == 2)
     {
        destinationStyle.Add(keyVal[0],keyVal[1]);
     }
  }
}

public static string GetStyleString(System.Web.UI.CssStyleCollection s, bool withName)
{
  string
style = (withName) ? "STYLE=\"" : ""; 
  foreach(string key in s.Keys)
 
{
    style += key + ":" + s[key] + ";";
  }

  style += (withName) ? "\"" : "";
  return
style;
}

-Brendan

Music tip of the day:  I've published some of the articles I write for the Portfolio magazine here.  Check em out!


Posted 10-23-2003 1:39 PM by Brendan Tompkins

[Advertisement]

Comments

Norman Rasmussen wrote re: The CssStyleCollection
on 05-26-2006 5:20 PM
The Trim() doesn't do anything, because it returns a new string which is lost.  The easy fix is to use keyvalpair.Trim().Split() instead.  In-fact you probably need to Trim the strings before adding them to the CssStyleCollection anyways.
Roger L. Main wrote re: The CssStyleCollection
on 10-09-2008 12:29 PM

Or you could try this (In VB - I don't do C#):

public sub copy_styles (source as cssstylecollection, destination as cssstylecollection)

   for each key in source.keys

       destination.add (key, source.item (key))

   next

end sub 'copy_styles

Just like a C# programmer to overcomplicate things ;)

change the style at the server « (slightly) Behind the Curve wrote change the style at the server « (slightly) Behind the Curve
on 05-14-2009 4:40 PM

Pingback from  change the style at the server « (slightly) Behind the Curve

Add a Comment

(required)  
(optional)
(required)  
Remember Me?