Myworld Myworld - 4 months ago 28
CSS Question

Add CSS class to a div in code behind

I have a div and I am trying to add a CSS class to it in code but I receive the following error when I try

Property or indexer 'System.Web.UI.HtmlControls.HtmlControl.Style' cannot be assigned to -- it is read only


I am using the following code:

protected void BTNEvent_Click(object sender, ImageClickEventArgs e)
{
BtnventCss.Style= "hom_but_a";
}


Can anyone please help me?

Answer

what if :

 <asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />

To add or remove a class instead of overwrite all classes with

   BtnventCss.CssClass = "hom_but_a"

keep the HTML correct:

    string classname = "TestClass";
    // add a class
    BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       );
     //remove a class
     BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       );

This assures

  • original classnames remain
  • there are no double classnames
  • there are no disturning extra spaces

Especially when client-side development is using several classnames on one element.

in your example use

   string classname = "TestClass";
    // add a class
    Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       ));
     //remove a class
     Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       ));

You should wrap this in a method/property ;)