challengeAccepted
challengeAccepted

Reputation: 7600

Cannot access the CSS class for a link button from Code behind

Can we include a CSS class from code behind for a link button?

I have been trying this for a while, but I was not able to get it done. It does not show a hyper link nor does CSS work. Please refer to my code and see where am I doing wrong.

string link1 = "google.com"
lblclick.Text = "<p>See what our page looks like by clicking " 
+ "<asp:LinkButton CssClass="+"linkclass" + ">" 
+ link1 + "</asp:LinkButton>

Upvotes: 0

Views: 3666

Answers (4)

Kimtho6
Kimtho6

Reputation: 6184

if you want to add a linkbutton to a panel from codebehind you will have to create it from code.

LinkButton lb = new LinkButtton();
lb.cssclass="linkclass";
lb.text = "foo";
panel1.Controls.Add(lb);

Upvotes: 2

Patrick
Patrick

Reputation: 17973

If lblclick is a Label, then you can't add a asp tag like LinkButton just like that.

If you can (or if you move the LinkButton to your markup) you need to add the runat="server" to be able to set properties like CssClass on it. If you just want a plain link you can add an anchor tag instead.

lblclick.Text = "<p>See what our page looks like by clicking 
<a href=\"" + link + "\" class=\"linkclass\">" + link1 + "</a></p>"

Actually, if you want a link to another page you shouldn't use LinkButton at all, but rather the HyperLink class. You can use the NavigateUrl property to set the url to open when clicking the link.

If you want to add it to your markup you do it like this

<asp:HyperLink
     NavigateUrl="http://www.example.com"
     CssClass="linkclass"
     Text="link1"
     runat="server" />

and if you want to do it dynamically in code you add it by creating it and adding it to your Controls collection.

HyperLink link = new HyperLink();
link.NavigateUrl = "http://www.example.com";
link.Text = "link1";
link.CssClass = "linkclass";
Controls.Add(link);

Just remember that when you add controls dynamically you should add it in your Page_Load event every time you load your page. If you don't want it to display set its Visible property to false and change it to true based on an event or something. Perhaps not as important when using a HyperLink, but good practice nonetheless. An example of when dynamic controls bite you if you don't is this question asked recently.

Upvotes: 0

Joachim VR
Joachim VR

Reputation: 2340

You can't just add ASP.NET markup as a textproperty in your code, ASP doesn't work like that. Create a Linkbutton btn = new LinkButton(), and add it: lblclick.Controls.Add(btn). Then you can edit the properties of btn as you please.

Upvotes: 1

Gabe
Gabe

Reputation: 50493

Create the LinkButton in code like this:

LinkButton linkButton = new LinkButton();
linkButton.CssClass = "linkclass";
linkButton.Text = "google.com";

Upvotes: 1

Related Questions