Tuesday, August 19, 2008

Sharepoint C# HTML Trick: Is this fluent programming or sleazy hack?

The challenge: writing custom sharepoint web-parts can be painful because there is no inline code markup. (and I'm NOT using the "smart part" )

How to write HTML using nothing but C#?
HTML is a tree just like any other AST.

This is the code I wanted to write:


<asp:Table Width="100%">
<asp:TableRow>
<asp:TableCell Width="100%" CssClass="headerRow">Alphabetical Search</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Width="100%">
<asp:GridView runat="server" Width="100%" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>



This is the code equivalent (plus databinding) using fluent constructors using C#:


protected override void CreateChildControls()

{

var dataFeed = new List

{

"one",

"two",

"three"

};

var gridView = new GridView

{

Width = new Unit("100%"),

DataSource = dataFeed,

Visible = true

};

gridView.DataBind();

var table = new Table

{

Width = new Unit("100%"),

Rows =

{

new TableRow

{

Cells =

{

new TableCell

{

Text = "Alphabetical Search",

CssClass = "headerRow"

}

}

},

new TableRow

{

Cells =

{

new TableCell

{

Controls =

{

gridView

}

}

}

}

}

};

Controls.Add(table);

base.CreateChildControls();

}




Nothing earth shattering here, but I actually dont mind using this syntax. This is the result:







Do you like it?

Labels: , ,

0 Comments:

Post a Comment

<< Home