Home > Articles > Web Development > ASP.NET

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.3. Creating ViewState-Enabled Control Properties

You want your control's properties to retain their state using ViewState.

Technique

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="AspNetCookbook" Namespace="AspNetCookbook" 
Assembly="AspNetCookbook" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Recipe0303</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">
 <AspNetCookbook:ViewStateControl id="ViewStateControl1" runat="server"/>
 <asp:linkbutton text="PostBack test" runat="server"/>
</form>

</body>
</html>

Comments

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.

See Also

Section 3.1, "Declaring a Simple Custom Control"

  • + Share This
  • 🔖 Save To Your Account