开发者

How do you programmatically apply a css class to an asp.net control?

I'm wo开发者_JS百科ndering 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!


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


It's just a string property of WebControl:

firstName.CssClass += " selected";


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


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!!


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" />  


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";
}


you can use attribute of ui controls

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜