Search code examples
asp.netmaster-pagesfindcontrol

change id of a server control in asp.net


Hai guys,

I used find control to find a list item of an unoreder list inside a master page from content page using this,

Control home = this.Page.Master.FindControl("list").FindControl("home");

Now i have to change the id of the control home to "current" because to apply css for it....


Solution

  • Do you know the Type of the control you're finding? Neither Control nor ListItem expose a CssClass property, however, ListItem does expose it's Attributes property.

    Update based on comment and other question:

    You should be using System.Web.UI.HtmlControls.HtmlGenericControl

    So something like this should work for you:

    HtmlGenericControl home = 
                        this.Page.Master.FindControl("list").FindControl("home")
                                                             as HtmlGenericControl;
    
    string cssToApply = "active_navigation";
    
    if (null != home) {
      home.Attributes.Add("class", cssToApply);
    }
    

    If you think there might already be an class assigned to it that you need to append to you could do something like:

    if (null != home) {
      if (home.Attributes.ContainsKey("class")) {
        if (!home.Attributes["class"].Contains(cssToApply)){
          // If there's already a class attribute, and it doesn't already
          // contain the class we want to add:
          home.Attributes["class"] += " " + cssToApply;
        }
      }
      else {
        // Just add the new class
        home.Attributes.Add("class", cssToApply);
      }
    }
    

    If they aren't ListItems, cast them to the correct type, and modify the attributes collection as before, unless there's a CssClass property for that type.