1

I want to change css from code-behind

If I have: <asp:TextBox ID="txt" CssClass="MyClass" runat="Server" />

I can do: txt.Visible = false; to hide the textbox.

But this will free up the space that the text box txt had. Instead I want to do something like:

txt.css("display", "none");

How can I achieve this in asp.net code behind?

Thanks

States
  • 141
  • 11
  • Why don't you put your textbox inside a div and make the div visible/invisible ? – Chandan Kumar Dec 11 '14 at 13:36
  • @mason - why can't ? we can make the div runat='server' and make div to be visible/invisible depending upon the condition – Chandan Kumar Dec 11 '14 at 13:39
  • That's what I was thinking too. But I am working on a project where they are using tables, and did not use div. It's made in a way that makes it bad to introduce div, since I have to do a lot of modifications many places – States Dec 11 '14 at 13:40
  • Then you can follow what Andrei answered. That's the solution for your requirement. – Chandan Kumar Dec 11 '14 at 13:42
  • Are you sure you got your methods the correct way round? I thought visibility:hidden _didn't_ free up space and so it should be what you want. Check [this answer](http://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone) – U r s u s Dec 11 '14 at 13:55

1 Answers1

3

Controls have a Style property which you can use to set specific CSS rules:

txt.Style["display"] = "none";

However specifying style in the html element directly is not recommended. Instead you might want to have a class, say hide, and append it to the control's css classes:

txt.CssClass += " hide";
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • Andrei, why is it not recommended? – States Dec 11 '14 at 13:43
  • 1
    @States, because inline styles tend to grow into totally unmaintainable thing. If this is just about display, that's probably fine, but for anything else it is better to have a reusable css class defined. – Andrei Dec 11 '14 at 13:46