htmlcsssharepoint-2010createchildcontrols

Which way of programmatically referencing a CSS class is most reliable?


In my Sharepoint project, I am dynamically creating controls in the overridden CreateChildControls() method. I don't know which of the two ways to reference the .css file is preferred:

protected override void CreateChildControls()
{
    base.CreateChildControls();

    // Way 1
    // from http://sharepoint.stackexchange.com/questions/18652/programmatically-add-js-css-to-pages
    this.Controls.Add(new CssRegistration()
    {
        Name = "/_layouts/ucsc_web_forms.css"
    });

    // Way 2
    HtmlLink cssLink = new HtmlLink();
    cssLink.Attributes.Add("type", "text/css");
    cssLink.Attributes.Add("rel", "stylesheet");
    cssLink.Attributes.Add("href", "/_layouts/duckbilled_platypi_rus.css");
    this.Page.Header.Controls.Add(cssLink);

    boxPayeeName = new TextBox();
    boxPayeeName.CSSClass = "duck-billed-platypi";
    boxPayeeName.Columns = LONG_TEXT_BOX_COL_WIDTH;
}

...but figure one of them, at least, should do the trick. Is one methodology to be preferred over the other?

UPDATE

Based on empirical observation (the empirical strikes back), the second "way" breaks the WebPart, at least mine. The first:

this.Controls.Add(new CssRegistration()
{
    Name = "/_layouts/ucsc_web_forms.css"
});

...at least "does no harm"


Solution

  • This works for me (assuming your project has a CSS file named "ucsc_web_forms.css" which has classes named "finaff-webform-field-label" and "finaff-webform-field-input"):

    Add the following to CreateChildControls() after "base.CreateChildControls();":

    this.Controls.Add(new CssRegistration()
    {
        Name = "/_layouts/ucsc_web_forms.css"
    });
    

    ...then, creating the dynamic controls likes so works just dandy:

    LiteralControl reqDateStr = new LiteralControl("<span class=\"finaff-webform-field-label\">Requester Date:</span>");
    . . .
    boxPayeeName = new TextBox();
    boxPayeeName.CssClass = "finaff-webform-field-input";