Monday, 21 April 2008

Maintain control state in ASP.NET

using System;
using System.ComponentModel;
using System.Web.UI;

[Serializable()]
[ToolboxData( "<{0}:MyControl runat=\"server\">" )]
public class MyControl: Control
{
[Serializable()]
private struct MyControlProperties
{
public int Property1;
public string Property2;
}

private MyControlProperties _properties = new MyControlProperties();

[DefaultValue( 0 )]
public int Property1
{
get
{
return _properties.Property1;
}
set
{
_properties.Property1 = value;
}
}

[DefaultValue( "" )]
public string Property2
{
get
{
return _properties.Property2;
}
set
{
_properties.Property2 = value;
}
}

protected override void OnInit( System.EventArgs e )
{
base.OnInit( e );

Page.RegisterRequiresControlState( this );
}

protected override object SaveControlState()
{
return _properties;
}

protected override void LoadControlState( object savedState )
{
_properties = (MyControlProperties)savedState;
}
}

No comments: