I am creating new elements for a webpage at run-time and I have code like this:

      var dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("Div") {ID = "dynDiv"};
      dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
      dynDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Height, "30px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
      dynDiv.InnerHtml = "New Object";

Is there a shorthand method to adding these value? I.e. something like:

dynDiv.Style.Add(HtmlTextWriterStyle {BackgroundColor = "Red", Position = "absolute; left: 500px; top: 500px", Height = "30px", Width="300px"});

Or any other easier way that anyone can suggest?


1 Answer 1


Under normal circumstances, you could use collection initializer to write your code this way:

var dynDiv = new HtmlGenericControl("Div")
    ID = "dynDiv",
    Style =
        { HtmlTextWriterStyle.BackgroundColor, "Red" },
        { HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px" },
        { HtmlTextWriterStyle.Height, "30px" },
        { HtmlTextWriterStyle.Width, "300px" }
    InnerHtml = "New Object"

Unfortunately, this code won't compile, because CssStyleCollection doesn't implement IEnumerable, which is a requirement for collection initializers.

  • \$\begingroup\$ OK, I'll have to stick with writing it the way I am. It just seems very verbose. As you state, there's normally shorter ways to do this type of thing. \$\endgroup\$
    – Family
    May 9, 2013 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.