How to make user controls know about css classes in ASP.NET

Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?

Edit: Or should I go for a different design like exposing css classes as properties like “HeaderStyle-CssClass” of GridView?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here’s what I did:

<link rel="Stylesheet" type="text/css" href="Stylesheet.css" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" id="style" runat="server" visible="false" />

It fools Visual Studio into thinking you’ve added a stylesheet to the page but it doesn’t get rendered.


Here’s an even more concise way to do this with multiple references;

<% if (false) { %>
    <link rel="Stylesheet" type="text/css" href="Stylesheet.css" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" />
    <script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>

As seen in this blog post from Phil Haack.

Method 2

Add the style on your usercontrol and import css in it.

 <%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WCReportCalendar.ascx.vb"
Inherits="Intra.WCReportCalender" %>
 <style type='text/css'>    
      @import url("path of file.css");
       // This is how i used jqueryui css
      @import url("https://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css");               

 </style>

 your html

Method 3

If you are creating composite UserControl, then you can set the CSSClass property on the child controls..

If not, then you need to expose properties that are either of the Style type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a style attribute to the HTML tags when rendering).

Method 4

You Can use CSS direct in userControl.

Use this in UserControl:

 <head>
    <title></title> 
    <style type="text/css">
      .wrapper {
          margin: 0 auto -142px; 
         /* the bottom margin is the negative value of the footer's height */ 
       }
    </style>
 </head>

This will work.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x