Developer
Developer

Reputation: 8636

applying css for <li> tag, ASP.Net which is in master page

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>

enter image description here 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

Answers (3)

शेखर
शेखर

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

Edit 1.

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

Tim B James
Tim B James

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

Gordon Copestake
Gordon Copestake

Reputation: 1637

try :

nav_members.Attributes.Add("class", value);

Upvotes: 0

Related Questions