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