Subscribe

RSS Feed (xml)

Creating ViewState-Enabled Control Properties

This example shows you how to create properties for your controls that retain their state
using ViewState.
The ViewStateControl class:

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Public Class ViewStateControl
Inherits System.Web.UI.WebControls.WebControl
Public Property [Text]() As String
Get
Dim _text As String = CStr(ViewState(“Text”))
If _text Is Nothing Then
Return String.Empty
Else
Return _text
End If
End Get
Set(ByVal Value As String)
ViewState(“Text”) = Value
End Set
End Property
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
writer.Write([Text])
End Sub
End Class
To use this control, you need to do the following:
<%@ Page language=”VB” %>
<%@ Register TagPrefix=”AspNet” Namespace=”AspNet”
Assembly=”AspNet” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” >
<html>
<head>
<title>code0303</title>
</head>
<body>
<script language=”VB” runat=”server”>
Sub Page_Load(Sender As Object, E As EventArgs)
If Not IsPostBack Then
Dim RandomGenerator As Random
RandomGenerator = New Random(DateTime.Now.Millisecond)
ViewStateControl1.Text = RandomGenerator.Next(1,100)
End If

End Sub
</script>
<form id=”Form1” method=”post” runat=”server”>
<AspNet:ViewStateControl id=”ViewStateControl1” runat=”server”/>
<asp:linkbutton text=”PostBack test” runat=”server”/>
</form>
</body>
</html>

This control property called Text will retain its state on postbacks—as you see, it is quite
easy to get properties to retain their state by using the ViewState property, and this
technique is recommended for most Web Control properties.

No comments:

Archives

Variety in the Web World