Monday, December 08, 2008

An easy way to add a stylesheet to a header from an ASP.NET control

This was suggested in a comment at the bottom of this codeproject article - really quite a neat solution :)

private bool AddStyleSheetToPageHeader(string uniqueId, string href)
{
if (Page.Header.FindControl(uniqueId) == null)
{
Literal l = new Literal();
l.Text = string.Format(@"<link rel="'stylesheet'" href="'{0}'" type="'text/css'">", href);
l.ID = uniqueId;
Page.Header.Controls.Add(l);
return true;
}

return false;
}


It means this can be written as Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.Scripts.Add(new ScriptReference(@"http://yui.yahooapis.com/2.6.0/build/utilities/utilities.js"));
scriptManager.Scripts.Add(new ScriptReference(@"http://yui.yahooapis.com/2.6.0/build/slider/slider-min.js"));
scriptManager.Scripts.Add(new ScriptReference(@"http://yui.yahooapis.com/2.6.0/build/colorpicker/colorpicker-min.js"));

if (AddStyleSheetToPageHeader("DesktopModules_SlodgeRoutes_SubControls_FilterSetupControl_ColorPicker", "http://yui.yahooapis.com/2.6.0/build/colorpicker/assets/skins/sam/colorpicker.css"))
{
// any one time init stuff
}
}
}

(Example shown is Yahoo UI Color picker)

1 comment:

  1. Thanks, I was looking for insert Javascript libs from C# and find here the missing magic spell ingredient ScriptManager.GetCurrent(this.Page).

    ReplyDelete