Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative in .Net to building Tables/TR/TD manually?

Tags:

.net

webforms

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 little static text.

like image 488
egrunin Avatar asked Dec 03 '25 17:12

egrunin


2 Answers

You could look at GridView in ASP.NET.

like image 188
Mark Byers Avatar answered Dec 06 '25 08:12

Mark Byers


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

like image 20
mamoo Avatar answered Dec 06 '25 08:12

mamoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!