tags:

views:

243

answers:

4

Hello everyone,

I've built a custom server control that uses custom CSS. The problem that I have is that I have to set a reference to the css file on each page I use the control.

Can I set this reference inside the control ? So that I could just add the control and not worry about the reference.

+2  A: 

Here what I use to add css reference to Page programmatically :

HtmlLink link = new HtmlLink();
link.Href = relativePath;
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
Page.Header.Controls.Add(link);

Maybe you should add some code to check if the css file added to the header control.

Canavar
Where should I embeed this in the custom server control ?
In which phase of the creation cycle ?
CreateChildControls is suitable, I think.
Canavar
A: 

You could do it with a ScriptManager - and this will also help you embed the stylesheet in the custom control library's DLL.

Or you could just reference the CSS from your master page. Unless you're packging a custom control library to sell etc, ScriptManager is a LOT of extra effort vs the Master Page solution

Rob Fonseca-Ensor
A: 

i would think you could add canavars code to a baseclass that would be included with all the classes that need it.

public class myclass : BaseClass
{
    var customCSS = customcss();
     Page.Header.Controls.Add(customCSS); }

and your baseclass:

public class BaseClass : Page
{
    public HtnlLink customcss(){
     HtmlLink link = new HtmlLink();
 link.Href = relativePath;
 link.Attributes["type"] = "text/css";
 link.Attributes["rel"] = "stylesheet";
 return link;
}

}

or you could go down the route of

myObject.Attributes.Add("style","width:10px; height:100px;");

or myObject.Attributes.Add("style",customStyle(););

where this is in your baseclass

public String customStyle()

{ return "width:10px; height:20px;"; }

and customstyle would be a function like so:

but i would assume that you use css for the rest of your site, so maybe a style could just be added to your stylesheet that you use on all pages through this method you could use the below code:

myObject.Attributes.Add("class","customControl");

this will then reference the correct CSS style from your main, always included stylesheet.

unless i am missing something here?????

minus4
A: 

If you want build webcontrol, that will be reusable and in one assembly with css, js and other resources, than you can use WebResources

Working with Web Resources in ASP.NET 2.0

Jan Remunda