Dragan Dragan - 21 days ago 4x
ASP.NET (C#) Question

Add aditional Css class programatically

I have a textbox with a Css class called 'required'. When a user click a button, I'd like to add aditional Css Class to the textbox called 'error' without removing the 'required' class. I want to acomplish this from code-behind. Thanks for taking the time to answer my question


You can set the CssClass property of the ASP.NET Textbox control. To add more than one CSS class for an element, just separate it with a space:

MyTextBox.CssClass = "class1 class2";

You can put this in your OnClick event handler:

<asp:TextBox ID="MyTextBox" runat="server" OnClick="MyTextBox_Click" />

Then in code-behind:

void MyTextBox_Click(Object sender, EventArgs e) {
    MyTextBox.CssClass = "class1 class2";