I have the following code which adds a label and a gridview to an asp.net page:
GridView grd = CreateGridView(kvp.Key.Text);
Label l = new Label();
l.Text = "some text";
l.CssClass = "this has no effect";
placeHolderResults.Controls.Add(l);
placeHolderResults.Controls.Add(grd);
Two questions really:
As the page will have a multiple and unknow quantity of Label + Grid pairs I'm looping through the above code, is this the best way to add the controls to the page?
I cannot style the label? How do you do it? Looking at the HTML which is created, the label turns out to be a SPAN.
Thanks in advance,
Jim
l.CssClass will only have effect if you put the class name from a style into it. For example:
<style type="text/css">
.boldText {text-weight: bold}
</style>
// then the following should work
l.CssClass = "boldText";
// this will generate: <span class="boldText">your text</span>
If you just want to add styling directly, then you can do the following:
l.Attributes.Add("style", "color:Red;font-weight:bold;");
// this will generate <span style="color:Red;font-weight:bold">your text</span>
I hope this helps. Have fun coding!
PS:
<asp:Literal>
always generates plain text <asp:Label>
generates <SPAN>
<asp:Panel>
generates <DIV>
EDITED on 2010.12.09 - fixed bugs in example code based on Jim's comment
Change it to RED BOLD:
lblMyLabel.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
lblMyLabel.Style["font-weight"] = "bold";
Change it to BLACK NORMAL:
lblMyLabel.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000");
lblMyLabel.Style["font-weight"] = "normal";
Use
System.Web.UI.HtmlTextWriterStyle
and method
public void Add(HtmlTextWriterStyle key, string value);
Sample:
Label label = new Label
{
Text = "some text";
CssClass = "yourClass"
};
label.Style.Add(HtmlTextWriterStyle.MarginRight, "12px");
parentControl.Controls.Add(label);
已经回答了类问题,对于要更改的“span”标签,我建议使用对象 HtmlGenericControl 并将属性 TagName 分配给所需的标签,例如:
HtmlGenericControl myControl = new HmtlGenericControl { TagName = "label"};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.