Reputation: 8636
Hi all I would like to apply css
for <li>
tag which is in master page dynamically from code behind this is my design
<div id="primary_nav">
<ul>
<li class="left active" id="nav_discussion" runat="server">
<a title="Go to Forums" href="">
Forums
</a>
</li>
<li class="left" id="nav_members" runat="server">
<a title="Go to Member List" href="Members.aspx">
Members
</a>
</li>
</ul>
</div>
In my content page I accessed <li>
as follows
Control li = Page.Master.FindControl("nav_members");
But I am unable to apply the required css
here can some one help me
Upvotes: 2
Views: 15059
Reputation: 17614
If you find the control then use following to add css
Control li = Page.Master.FindControl("nav_members");
li .Style.Add("float", "left");
If you want to override some property then you can use
li .Style.Add("width", "100px !important");
etc.Here is a good link
What are the implications of using "!important" in CSS?
Here is a similar question
C# - How to change HTML elements attributes
You need to cast it in a html generic control first
HtmlGenericControl li = (HtmlGenericControl)(Page.Master.FindControl("nav_members"));
li .Style.Add("width", "100px !important");
Upvotes: 2
Reputation: 20364
In this case, your Control
is of type HtmlGenericControl
which does not contain a property for CssClass
.
You will need to cast your control to type HtmlGenericControl. e.g.
System.Web.UI.HtmlControls.HtmlGenericControl li = (System.Web.UI.HtmlControls.HtmlGenericControl) this.Page.Master.FindControl("nav_members");
This will then give you two choices to apply the style to the element. You can either use the Style
property or the Attributes
property.
The Style
property will allow you to add inline styling to the element e.g.:
li.Style.Add("Color", "Black");
This will render the element with:
style="color:red;"
Your other option is to use the Attributes
property which will allow you to add the class
.
li.Attributes.Add("class", "nameofyourclass");
Read more about the HtmlGenericControl
Upvotes: 6