ASP.NET Custom Server Controls: Cute ASP.NET TextBox Control - Understanding the MyTextBox
(Page 4 of 6 )
In this section, we shall go into the details of the “MyTextBox” custom control. First of all let us consider the following line:
Public Class MyTextBox
Inherits System.Web.UI.WebControls.WebControl
Implements IPostBackDataHandler
I already explained that any custom control (or class of custom control) needs to be derived either from System.Web.UI.Control or System.Web.UI.WebControls.WebControl. The above statement does exactly this. Until there we are all right. But what is the use of “IPostBackDataHandler”? This is the interface we need to implement to support the feature of “postback.” We shall see its details later. Let us proceed to the following code fragment:
Property [Text]() As String
Get
Return viewstate("text") & ""
End Get
Set(ByVal Value As String)
viewstate("text") = Value
End Set
End Property
I hope you can understand the above. I define a property named “text,” which has the “viewstate” support. Any information we store in “viewstate” would exist to the server even after further web requests from the same page in a magical manner.
All of the information available in “viewstate” will be encoded and added to a hidden field to the same page by the ASP.NET runtime. When a post back occurs, all the information in that hidden field again gets posted to the server along with new pairs of values. We then check (or compare) the previous values (or information in viewstate) with recently modified values by the user and modify the view state accordingly during a “postback” event. This could be observed better from the next section.
Continuing with the above code, we have:
Protected Overrides Sub Render(ByVal output As System.Web.UI.HtmlTextWriter)
MyBase.AddAttributesToRender(output)
output.AddAttribute (HtmlTextWriterAttribute.Name, Me.UniqueID)
output.AddAttribute (HtmlTextWriterAttribute.Id, Me.ClientID)
output.AddAttribute (HtmlTextWriterAttribute.Type, "text")
output.AddAttribute (HtmlTextWriterAttribute.Value, Text)
output.RenderBeginTag (HtmlTextWriterTag.Input)
output.RenderEndTag()
End Sub
The above code fragment is at the heart of displaying the “textbox.” First of all, I add all the attributes of the “input” tag such as name, id, type, value, and so forth using the “output.AddAttribute” method. “UniqueID” and “ClientID” are automatically generated when a control has been dragged from the toolbox on to the web form.
“MyBase.AddAttributesToRender(output)” is the statement which is essential to making it available as the first statement. All of the default attributes, such as “style” (what we set at design time using the properties window) will be added using that simple statement. If you forget that statement, you will be left with a very plain textbox without having any of your design time properties set.
Next: Handling the “PostBack” from “ViewState” >>
More ASP.NET Articles
More By Jagadish Chaterjee