Manish
Manish

Reputation: 6286

How to add style from code behind?

I want to add a style A:Hover to a HyperLink control from code behind.

I can do like this :

HyperLink hlRow = new HyperLink();
hlRow.Style.Add("color", "#000000");
hlRow.Style.Add("text-decoration", "none");

But how can I add styles for A:Hover for the hyperlink control? Do I need to define a class and associate that class with this control, if yes how?

Upvotes: 20

Views: 115727

Answers (8)

vivek verma
vivek verma

Reputation: 1

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

Upvotes: -2

denjerlog
denjerlog

Reputation: 11

If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:

.disabled {
    color: grey;
    text-decoration: none !important;
}

LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";

Upvotes: 1

bydoga
bydoga

Reputation: 173

Use

HyperLink hlRow = new HyperLink();
hlRow.Attributes.Add("Style", "color:#000000");

Upvotes: 17

bat
bat

Reputation: 21

Also make sure the aspx page has AutoEventWireup="true" and not AutoEventWireup="false"

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55062

You can't.

So just don't apply styles directly like that, and apply a class "foo", and then define that in your CSS specification:

a.foo { color : orange; }
a.foo:hover { font-weight : bold; }

Upvotes: 0

m3kh
m3kh

Reputation: 7941

Try this:

Html Markup

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">HyperLink</asp:HyperLink>

Code

using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
    Style style = new Style();
    style.ForeColor = Color.Green;
    this.Page.Header.StyleSheet.CreateStyleRule(style, this, "#" + HyperLink1.ClientID + ":hover");
}

Upvotes: 5

Mostafa Elmoghazi
Mostafa Elmoghazi

Reputation: 2154

You can use the CssClass property of the hyperlink:

LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        background-color:Red;
                    }
                    .d:hover
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
        this.HyperLink1.CssClass = "d";

Upvotes: 25

David Hedlund
David Hedlund

Reputation: 129782

:hover is a selector, and not a style. What you're doing in your example is adding inline styles to an element, and a selector equivalent for that obviously doesn't make much sense.

You can add a class to your link: hlRow.CssClass = 'abc'; And define your class as such:

a.abc:hover {
    ...
}

Upvotes: 3

Related Questions