tags:

views:

108

answers:

3

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?

+1  A: 

The Style property gets a collection of all the cascading style sheet (CSS) properties, you cannot set it.

Try BtnventCss.CssClass = "hom_but_a"; instead.

I'm assuming BtnventCss is a WebControl.

Just seen you're probably using <div runat="server"...

If so, you can try:

BtnventCss.Attributes.Add("class", "hom_but_a");  

You could make the div an asp:panel - they will render the same and you'll get better server-side support.

Joe R
+1  A: 

div with runat="server" is mapped to a HtmlGenericControl. Try using BtnventCss.Attributes.Add("class", "hom_but_a");

Vinay B R
A: 

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 ;)

Caspar Kleijne