How To Embedded StyleSheet File with Custom Control.

How to embedded StyleSheet file with custom control? Question has been opened many time on ASP.NET forum.

So in this article, I will try to demonstrate how to achieve this task.

In General

In general, if you want to embedded any thing with custom control, you need first to make its "Build Action" property to be "Embedded Resource", and then you need to add to the custom control assemblies using the <Assembly> attribute typically above class name, and finally you need to register in the page so it can be rendered.

I will illustrate all these things in details through the article.

 

Step One: make it as Embedded Resource

 After you added the StyleSheet file to your Custom Control Class Library project, first thing you need to do is to make build action property for the stylesheet file as embedded resource, otherwise your page will not be able to see the stylesheet file.

To do this, from the VS do a right click on the stylesheet file, and click on Properties,  and then change the "Build Action" property to be "Embedded Resource".

 

Step Two: Add it to the Custom Controls Assemblies

 Second thing you need to do is to register the Css file to the custom control assemblies by adding the below code typically above class name


[assembly: WebResource("YourProjectName.StyleSheetFileName.css", "text/css")]

namespace YourNameSpace

{

   public class MyCustomControl : CompositeControl

    {

       //Custom Control Rest Code

 

 Step Three: Register Css File on the Page

Finally, we have to tell the Page that our custom control has Css file needed to be registered when the final HTML is generated for that page. So we need to write a bit of code in the OnInit method.

 

protected override void OnInit(EventArgs e)

{

    base.OnInit(e);

   

    string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(this.GetType(),

    "YourProjectName.CssFileName.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";

   

               

    Page.ClientScript.RegisterClientScriptBlock(this.GetType, "cssFile", css, false);

}

 

And that's it, you can now use the CSS StyleSheet file within your Custom Control.

 

I hope some one will found this very helpful.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值