2

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

1
  • <li class="left" id="nav_members" runat="server"> I make this as server control na?
    – Developer
    Jan 30, 2013 at 8:59

3 Answers 3

6

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

2

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");
1
  • li .Style.Add("float", "left"); after . I am unable to get Style or attributes.add that's why I asked
    – Developer
    Jan 30, 2013 at 9:06
0

try :

nav_members.Attributes.Add("class", value);
1
  • In a normal web page this works, but I would like to call this from master page
    – Developer
    Jan 30, 2013 at 9:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.