开发者

change id of a server control in asp.net

Hai guys,

I used fi开发者_运维技巧nd 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....


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.


Yes, to use css id's in asp.net is a big problem. first of all you can change your server control's id to what you want but, this will be regenerated by ASP.NET depending on the position of the control in your page's control tree.

My recommendation is to use cssclass property of the controls, and to replace the css ids to class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜