alternative in .Net to building Tables/TR/TD manually?
I've got a pile of code here that looks like this:
if (stateTax > 0)
{
tr = new TableRow();
tbl.Rows.Add(tr);
td = new TableCell();
td.CssClass = "stdLabel";
td.Text = "NY State Tax";
tr.Cells.Add(td);
td = new TableCell();
td.Text = string.Format("{0:C}", stateTax);
td.CssClass = "justRight";
tr.Cells.Add(td);
}
This is a horrible hash of data and layout, but creating a special class or control every time something like this comes up seems almost as bad.
What I usually do is write a helper function, which is concise but ugly:
if (stateTax > 0)
MakeRow(tbl, "NY State Tax", "stdLabel",
string.Format("{0:C}", stateTax), "justRight");
And now I'm thinking: haven't I done this 100 times before? Isn't there a more modern way?
Just to be explicit: it's a whole list of miscellaneous labels and values. They don't come from any particular data source, and the rules for when rows should be suppressed vary. This example has only two columns, but I have other places with more.
Edited to emphasize: this kind of data is not naturally suited to a Repeater or GridView.
I use a Repeater for the Items in the ShoppingCart, it's a simple list. This is not such a list, it's what comes after: State Tax, City Tax, Shipping, Discounts, Special Instructions, Gift Labels, and explanatory boilerplate. Very miscellaneous, often optional, but there needs to be some kind of organizing layout or it looks wrong.
I could create a custom List of some sort and dump everything in just so I can use a Repeater, and sometimes I do that; but it's still a hack.
I suppose I could make each item a Control
, with Visible = false
, then reveal what's needed at runtime. But it still feels like a lot of coding for laying out a l开发者_JS百科ittle static text.
You could look at GridView in ASP.NET.
Whenever possible, avoid to bind code-behind logic with presentation stuff. In this particular case you can achieve the same goal with a Repeater
You can take a look to a fairly simple example here...
http://articles.sitepoint.com/article/asp-net-repeater-control
You might want to look into binding to a GridView control instead.
However, I never use this pattern anymore. Now all of my grids are JavaScript based and use Ajax to retrieve the data to load into them.
I can think of two ways you could accomplish what you want to do...
Make a User Control or a Custom Control and write your data to the Properties contained within.
Just drop a Literal control on the page then fill it with whatever you want when you write your page. A literal is exactly as it says, literal. If you set it's text property to... "hello world" this is exactly what will go into the html and when the page is rendered you'll see a single row table containing the text 'hello world'.
精彩评论