Jestus Jestus - 6 months ago 398
CSS Question

ASP.NET Button with Bootstrap Glyphicon

I'm attempting to use glyphicons as icons for ASP

Button
.

I know you can easily do this by giving the
<i>
element the proper
glyphicon
CSS, and then parent it under the desired button.

However, I want to do this from the C# side NOT HTML. How do I do this?

I tried the following, to no avail:

HtmlGenericControl i1 = new HtmlGenericControl("i");
i1.Attributes["class"] = "glyphicon glyphicon-backward";
i1.Attributes["aria-hidden"] = "true";

Button btnFirst = new Button();
btnFirst.ID = "btnFirst";
btnFirst.CommandName = "FirstPage";
btnFirst.CssClass = "btn btn-default pageButton";
btnFirst.Click += new EventHandler(btnFirst_Click);
btnFirst.Controls.Add(i1);
container.Controls.Add(btnFirst);


If I run this as above, the button is shown, but there is no icon.
In the HTML, there is no
<i>
element nested beneath the button. In fact, it appears to no exist.

Answer

For your button to have a child element, use LinkButton instead of using Button:

LinkButton btnFirst = new LinkButton();

The Button is rendered to <input type='button'> that doesn't allow any child elements.

LinkButton is rendered by .NET to <a> so it will work, and btnFirst's EventHandler will be kept as well.

Comments