ASP.NET: How to set the cssclass for a menuitem on codebehind

烈酒焚心 提交于 2019-12-08 07:33:37

问题


How can I set a different cssclass for each menuitem of a ASP.NET Menu control from codebehind? All of these menuitems are at level2. So something like this would not work because all of the menuitems on level2 would end up with the same cssclass(level2class) and I want to be able to set diferent styles for each of them:

<LevelMenuItemStyles>
    <asp:MenuItemStyle CssClass="level1class"/>
    <asp:MenuItemStyle CssClass="level2class"/>    
</LevelMenuItemStyles>

So I'd like to do something like this:

MenuItem myMenu = new MenuItem();
myMenu.Text = "MyMenu";
Menu1.Items.Add(myMenu); //Menu1 is the name of the asp.net Menu control

foreach (DataRow row in myDataTable.Rows)
 {
    MenuItem myItem = new MenuItem();
    string myItemName = row["myItemName"].ToString();
    myItem.Text = myItemName; 

    //HERE COMES THE PROBLEM. I'M NOT ABLE TO DEFINE A DIFFERENT CSSCLASS FOR EACH MENUITEM.
    if (myItemName == "x1")
    { 
          myItem.CssClass = "x1class";  //THIS DOES NOT WORK AS MENUITEM DOES NOT HAVE CSSCLASS PROPERTY
    }
   else if (myItemName == "x2")
   {
         myItem.CssClass = "x2class";  //THIS DOES NOT WORK AS MENUITEM DOES NOT HAVE CSSCLASS PROPERTY
   }

   myMenu.ChildItems.Add(myItem);
}

ANOTHER TRIED ALTERNATIVE THAT COULD WORK BUT AM STUCK ALSO:

if (myItemName == "x1")
 { 
     MenuItemStyle ms = new MenuItemStyle();
     ms.CssClass = "x1class";
     //HOW DO I SET ms OBJECT TO THE myItem OBJECT?
}
else if (myItemName == "x2")
{
     MenuItemStyle ms = new MenuItemStyle();
     ms.CssClass = "x2class";
     //HOW DO I SET ms OBJECT TO THE myItem OBJECT?
}

Thank you


回答1:


But if you really want to a CSS class you might be able to use the Attributes.Add method... something like this myItem.Attributes.Add( "class", "pretty" );



来源:https://stackoverflow.com/questions/19883721/asp-net-how-to-set-the-cssclass-for-a-menuitem-on-codebehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!