1

I'm wondering how I can apply a CSS class to an ASP.NET Control (TextBox in this case) through the backend in C#. For example:

<asp:TextBox ID="firstName" CssClass="input left" runat="server" Text="First Name" />

I'd like to add another class to the element "selected" if a value is true that I test for on the backend.

<asp:TextBox ID="firstName" CssClass="input left selected" runat="server" Text="First Name" />

What is the best way to do this? Thanks!

1
  • from this I'd like to add another class to the element "selected" if a value is true that I test for on the backend. it seems you wanted to check for a expression that evaluates to true/false . what do you want to test? Commented Sep 27, 2011 at 15:41

7 Answers 7

5

You can just do this:

 firstName.CssClass = "input left selected".

If you want to append to any existing class names, do this:

firstName.CssClass += " selected";
Sign up to request clarification or add additional context in comments.

Comments

0

It's just a string property of WebControl:

firstName.CssClass += " selected";

Comments

0
if(yourCondition) {
    var css = "myClass";
    if(String.IsNullOrWhiteSpace(element.CssClass))
        element.CssClass = css;
    else
        element.CssClass += " " + css;
}

Comments

0

I think you could do that in the normal way something like below:

      if (value.Equals(true))
       {
            firstName.CSSClass = "input left selected";
       }

Hope this helps!!

Comments

0

Simply create an entry in the ViewDataDictionary for the class.

The backend would look something like

ViewData["selectedclass"] = <conditionalstatement> ? "selected" : "";

And the view would be

    <asp:TextBox ID="firstName" CssClass="input left <%= ViewData["selectedclass"]%>" runat="server" Text="First Name" />  

Comments

0

You can implement adding cssClass like

firstName.CssClass = "input left selected";

Or

make onClick event for textbox

<asp:TextBox ID="firstName" CssClass="input left" runat="server" Text="First Name" OnClick="firstName_Click"  />

Then in code-behind:

void firstName_Click(Object sender, EventArgs e) {
    MyTextBox.CssClass = "input left selected";
}

Comments

0

you can use attribute of ui controls

firstName.Attributes["css"]="Your Class Name";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.