DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Add css class dynamically from code-behind file for HTML/ASP.NET controls

By Ashok Nalam on 17 Feb 2014 | Category: ASP.NET | Tagged: css class C# 
  Discuss Add Comment   |  
Add rating Rate this resource   
The tip shows how to assign CSS class dynamically through ASP.NET code behind file for HTML controls and ASP.NET controls.

Sample CSS:
.clsbgcolor
{
  background-color:red;
}

HTML controls:

We can't access HTML controls directly in code behind file. So in order to access HTML control add  runat="server" tag to HTML code.
<div id="mydiv" runat="server"></div>
In code behind assign CSS class to div control
protected void Page_Load(object sender, EventArgs e)
{
     mydiv.Attributes.Add("class", "clsbgcolor");
}

ASP.NET controls:

For ASP.NET server side controls directly we can use cssClass property.
<asp:panel runat="server" id="pnl"></asp:panel>
protected void Page_Load(object sender, EventArgs e)
{
    pnl.CssClass = "clsbgcolor"
}
Note: If you are using external CSS file make sure that you have added reference to page.
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (1)
 
1. By Laxminarayana on 14 Sep 2020

Thank you

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys