Tutorial :Setting a class for a DIV that is a server control



Question:

I different CSS styles, one of which is:

#layoutsectiondiv{      border: 2px dashed #000000;      padding: 1px;      left: 0px;  }  

I have a aspx page:

<div id="testDiv" runat="server">    </div>  

If it was regular HTML, I would set the style of a div by doing a

<div id="layoutsectiondiv">    </div>  

At runtime (in code behind), I need to dynamically assign different styles to the DIV. How would I do it?


Solution:1

Use the class property and change your css styles to use class selectors instead of id selectors. For example

.layoutsectiondiv{}    <div id="testDiv" class="layoutsectiondiv">  </div>  

Edit

Make your class only so that you apply it on the specific divs you want. don't reuse your classes. This should be easy since your css is already tied to a specific ID, just put that class on that element.

If you use that class on many types of elements what you suggested would work fine.


Solution:2

Josh is right, you should use class instead of id.

for your question :

At runtime (in code behind), I need to dynamically assign different styles to the DIV. How would I do it?

try this :

// layoutsectiondiv is defined as class : .layoutsectiondiv{}  testDiv.Attributes["class"] = "layoutsectiondiv";  


Solution:3

So you could use a css id selector this way.

#layoutsectiondiv { color: red }  

with the following html

<div id="layoutsectiondiv">      </div>  

Or a css class html selector like this.

.layoutsectiondiv { color: blue }  

with the following html

<div class="layoutsectiondiv">  </div>  

If you want to control the style of a particular .net control, ie one that has the runat="server" attribute, then as we know .net will 'mangle' the id to ensure its unique.

In this case in our code we can use FindControl to access the div and change its style

<div id="testDiv" runat="server">  </div>  

ie.

        HtmlGenericControl testDiv =              (HtmlGenericControl)Page.FindControl("testDiv");            // to hide          testDiv.Attributes.Add("style", "display: none");  // OR          testDiv.Attributes["style"] = "display: none";            // to show          testDiv.Attributes.Add("style", "display: block"); // OR          testDiv.Attributes["style"] = "display: block";            // or to add a class          testDiv.Attributes.Add("class", "MyCssClassName"); // OR          testDiv.Attributes["class"] = "MyCssClassName";  

Here is a good explanation on the difference between css id and class - CSS: div id VS. div class.

And here for How to edit CSS style of a div using C# in .NET


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »