Reference: CoDe Magazine - Creating ASP.NET Custom Controls with Style
My Notes:
* A control's Render method will render a control in the last step of a control's life cycle, just before the control is disposed.
* The only parameter for Render method is an HtmlTextWriter object.
* HtmlTextWriter object writes HTML to the output stream. It provides a set of Write methods.
By default, ASP.NET renders HTML 3.2 for all non-Microsoft browsers that does support HTML 4.0 and CSS properly.
* It's better practice to use CSS.
<p style="color:red">My Text</p>
is better than
<p><font color="red">My Text</font></p>
Create different HTML for different browsers:
* To check the type of requesting browser: use HttpBrowserCapabilities
HttpBrowserCapabilities client = Page.Request.Browser;
if (client.Browser == "IE")
{
if (client.MajorVersion > 6)
{
writer.Write("You are using IE 7.0 or above.");
}
else
{
writer.Write("You are using IE 6.0 or below.");
}
}
else
{
writer.Write("You are not using IE");
}
* Besides checking the browser type, the alternative way is to check the type of HtmlTextWriter passed to the Render method. It can be either HtmlTextWriter or Html32TextWriter.
* HtmlTextWriter: indicates that a browser supports HTML 4.0 with CSS.
* Html32TextWriter: indicates the browser only supports HTML 3.2 without CSS.
Downside: All non-Microsoft browsers, including Netscape versions that do support CSS, pass Html32TextWriter to the Render method.
if (writer.GetType().ToString() == "HtmlTextWriter")
{
//Render CSS
}
else
{
//Render HTML 3.2
}
#METHOD 1: Basic HTML output
writer.Write("<H2>" + _message + "</H2>");
#METHOD 2: Create HTML with Write & WriteLine
writer.WriteLine("<p>");
//Indent HTML by inserting a Tab
writer.Write(HtmlTextWriter.DefaultTabString);
//Make text red with Font tag
writer.Write("<font color=\"red\">");
writer.Write(_message);
writer.WriteLine("</font>");
writer.WriteLine("</p>");
#METHOD 3: Using Writer Helper methods to create HTML
writer.WriteFullBeginTag("p");
//Indent HTML by inserting a Tab
writer.Write(HtmlTextWriter.DefaultTabString);
//Make text blue with Font tag
writer.WriteBeginTag("font");
writer.WriteAttribute("color", "blue");
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(_message);
writer.WriteEndTag("font");
writer.WriteEndTag("p");
#METHOD 4: Writing Styles
//Write begin tag without closing >
writer.WriteBeginTag("p");
//Add a style
writer.Write(" style");
writer.Write(HtmlTextWriter.EqualsDoubleQuoteString);
writer.WriteStyleAttribute("color", "green");
writer.Write(HtmlTextWriter.DoubleQuoteChar);
//Output the '>' for the 'p' tag
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(_message);
//Write end tag
writer.WriteEndTag("p");