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?
If your div has runat="server" then you directly use this: divAllItemList. Attributes["class"] = "hidden"; Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM.
If you want to add attributes, including the class, you need to set runat="server" on the tag. Thanks, I was sure it would be this simple. @Tyler, no. This adds a new class name to the control.
addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.
HTML elements can belong to more than one class. To define multiple classes, separate the class names with a space, e.g. <div class="city main">. The element will be styled according to all the classes specified.
What if:
 <asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />   To add or remove a class, instead of overwriting 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
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With