Creating ViewState-Enabled Control Properties (C#)
<%@ Page language="C#" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Random rand = new Random();
ViewStateControl1.Text = rand.Next(1,100).ToString();
}
}
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Creating ViewState-Enabled Control Properties</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<Control:ViewStateControl id="ViewStateControl1" runat="server" />
<asp:linkbutton text="PostBack test" runat="server" />
</form>
</body>
</html>
File: Control.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace Control
{
[DefaultProperty("Text"),
ToolboxData("<{0}:ViewStateControl runat=server></{0}:ViewStateControl>")]
public class ViewStateControl : System.Web.UI.WebControls.WebControl
{
public string Text
{
get
{
string text = (string) ViewState["Text"];
return (text == null)? string.Empty : text;
}
set
{
ViewState["Text"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(Text);
}
}
}
Related examples in the same category