“Templating” the output is a simple task with one thing in mind – to give common output. The short-fall of “templating” your output is the following:
-
You may run into naming problems with siblings.
-
Functionality cannot be used. The controls are never added into the page's life stream; therefore, no interaction may occur.
The example that I am going to demonstrate with “templated” output is a score board for a soccer match. The example will be a very simple one with no fancies – this article is only here to demonstrate the technique, not a how-to example.
The score board will have four properties – two integers for the score; and, two strings for the names of the sides (namely, home team and visiting team). This is the basic definition that our server control will take:
public class TemplatedScoreBoard : Control {
private string pHomeName;
private string pVisitorName;
private int pHomeScore = 0;
private int pVisitorScore = 0;
public string HomeName {
get { return pHomeName; }
set { pHomeName = value; }
}
public string VisitorName {
get { return pVisitorName; }
set { pVisitorName = value; }
}
public int HomeScore {
get { return pHomeScore; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException();
else
pHomeScore = value;
}
}
public int VisitorScore {
get { return pVisitorScore; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException();
else
pVisitorScore = value;
}
}
}
And here is the code that makes up the “templated” output:
protected override void Render(HtmlTextWriter writer) {
Table table = new Table();
TableRow headerRow = new TableRow();
TableCell headerCell = new TableCell();
TableRow homeTeamRow = new TableRow();
TableCell homeTeamNameCell = new TableCell();
TableCell homeTeamScoreCell = new TableCell();
TableRow visitorTeamRow = new TableRow();
TableCell visitorTeamNameCell = new TableCell();
TableCell visitorTeamScoreCell = new TableCell();
table.Width = Unit.Percentage(100);
headerCell.ColumnSpan = 2;
headerCell.HorizontalAlign = HorizontalAlign.Center;
headerCell.Text = "Score Board";
headerCell.Style.Add("font-size", "22px");
headerCell.Style.Add("font-weight", "bold");
headerRow.Cells.Add(headerCell);
table.Rows.Add(headerRow);
homeTeamNameCell.Text = HomeName;
homeTeamScoreCell.Text = HomeScore.ToString();
homeTeamScoreCell.Width = Unit.Percentage(15);
homeTeamRow.Cells.Add(homeTeamNameCell);
homeTeamRow.Cells.Add(homeTeamScoreCell);
table.Rows.Add(homeTeamRow);
visitorTeamNameCell.Text = VisitorName;
visitorTeamScoreCell.Text = VisitorScore.ToString();
visitorTeamScoreCell.Width = Unit.Percentage(15);
visitorTeamRow.Cells.Add(visitorTeamNameCell);
visitorTeamRow.Cells.Add(visitorTeamScoreCell);
table.Rows.Add(visitorTeamRow);
table.RenderControl(writer);
}
Note that the Table control is never, ever added to the Controls collection – that is why the Table control does not exist in the page life cycle.