ASP.NET Custom Server Controls: Cute ASP.NET TextBox Control Continued - Understanding the life cycle – Attributes
(Page 3 of 5 )
In the previous section, we saw the methods implemented for rendering the control. But, we didn’t deal much with the “AddAttributesToRender” method. In this section, we will discuss it.
The “AddAttributesToRender” method is basically used (or overridden) to add HTML attributes and styles that need to be rendered for the respective custom control. In my solution, it has been implemented as follows:
Protected Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
.
.
writer.AddAttribute (HtmlTextWriterAttribute.Name, Me.UniqueID)
writer.AddAttribute (HtmlTextWriterAttribute.Id, Me.ClientID)
writer.AddAttribute (HtmlTextWriterAttribute.Type, "text")
writer.AddAttribute (HtmlTextWriterAttribute.Value, Text)
writer.AddStyleAttribute (HtmlTextWriterStyle.BorderColor, ColorTranslator.ToHtml (Color.DarkGray))
writer.AddStyleAttribute (HtmlTextWriterStyle.BorderStyle, "solid")
writer.AddStyleAttribute (HtmlTextWriterStyle.BorderWidth, "1px")
.
.
EndSub
I removed some of the statements (explained later) from the above method for the sake of clarity. Within the above method, if you carefully observe, you will see that the first statement is “base.AddAttributesToRender(writer)”. Is this necessary? Of courseit is. It is always a good practice to have the statement “Base.AddAttributesToRender(Writer)” as the first statement within the above method. Never remove it (unless you have any reason to do so). There also exists one more secret behind it.
During the design time of VS.NET, you may be moving the control to your favorite location (or adjusting its size, or changing some of its properties, or so on). All that information (say CSS) would be remembered and written back to our control using this statement. If you forget this statement, your control works in a floating manner at the left-top of the web page (without having any design time attributes set).
You must have observed that there exist some statements starting with “writer” as follows:
writer.AddAttribute (HtmlTextWriterAttribute.Value, Text)
writer.AddStyleAttribute (HtmlTextWriterStyle.BorderColor, ColorTranslator.ToHtml (Color.DarkGray))
The first statement (writer.AddAttribute) is generally used to emit an attribute of a tag. You can use all existing attributes from “HtmlTextWriterAttribute” or simply provide your own string in quotations. The second statement (writer.AddStyleAttribute) is generally used to add style (or inline CSS) to a tag. You can use all existing styles from “HtmlTextWriterStyle” or simply provide your own string in quotations. Finally, I am happy to say that we have “ColorTranslator” to emit .NET based color constants to HTML based color constants.
Next: Cute Features of this control >>
More ASP.NET Articles
More By Jagadish Chaterjee