0

I have a web control that I would like to modify the CSS class under certain conditions.

Ideally, I would like to write something like:

myMenu.StaticMenuItemStyle.CssClass = (".bgColor", "{background:#ff0000}");

Unfortunately, this is a third party control, and it does not expose any Style or Attribute properties. The only property exposed is CssClass. The problem is that the hex color is retrieved from the database, so I cannot have it predefined ahead of time in a css file.

EDIT: I don't know the HEX value to use for the background until OnPreRender() where I fetch the HEX value from the DB. At this point, I need to create/modify a css class by inserting/updating the HEX value for the background.

How can I programmatically create and assign a css class?

9
  • can't we do it with jquery? Commented Apr 24, 2017 at 1:34
  • No. Javascript yes. Commented Apr 24, 2017 at 1:39
  • 1
    You can still use CSS selectors to select the elements, even if they don't have a specific class assigned to them. Commented Apr 24, 2017 at 1:39
  • Write the css class in the page head during page load and use it here Commented Apr 24, 2017 at 1:40
  • How do I write css class in page head during page load? In other words the Page_Load ASP.NET event. Commented Apr 24, 2017 at 1:41

2 Answers 2

2

First apply a css class to you control and Crete style sheet in page header as below

//// Create dynamic style rule which applies to the CSS class selector (".MyCssClass")
Style dynamicClassStyle = new Style();
dynamicClassStyle.BorderStyle = BorderStyle.Solid;
dynamicClassStyle.BorderColor = System.Drawing.Color.Black;
dynamicClassStyle.BorderWidth = new Unit(1);
dynamicClassStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicClassStyle, null, ".MyCssClass");

Full article here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Exactly what I was looking for.
0

There are couple of ways:

Option-1 Keep all predefine css classes for all possible background colors and choose one based upon DB hex value.

Option-2: Create an empty CustomeStyle.css file. Add this CSS file reference in your website. Fetch the hexcode from DB and write a css class by opening the customstyle.css file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.