473,543 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Viewstate and Dynmac controls

All,

I have a CONTROL that contains 1 control (Control ONE), the 1 control that
it can contain 1 or 2 control (Control A and B).

Control A, raises and event and Control ONE receives this event and this
causes control B to be created, when this is done the VIEWSTATE is lost for
CONTROL B.

In the EVENT that causes CONTROL B to be created I have to set
ChildControlsCr eated to false, if I don't set it the viewstate works but the
control doesn't show, as the createchild controls does not get re-ran.

Below is the a smaller version of the code that I have created to reproduce
the problem test as follows :

Click Get Current Time, it will now show the time
Click do post back, it will still show time in first step, as well as time
of post back, to prove its posted back.
Click Raise Event, it has now lost the viewstate, time has gone blank.
Click Get Current Time on both line, you will see the time get filled in and
it persisted in the viewstate, do a few clicks to prove this.
Now Click Raise Event, view state has been lost again.

Cheers

Steve

Project name should be ViewStateTest

Code : (Add to single class called controls.cs)

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ViewStateTest
{
public class ContainTime : WebControl ,INamingContain er
{
ShowTime showtimeA;
ShowTime showtimeB;

WebControl holdingcontrol;

bool showB;

protected override void LoadViewState(o bject savedState)
{

base.LoadViewSt ate (savedState);
if (ViewState["ShowB"] == null)
{
showB = false;
}
else
{
showB = (bool) ViewState["ShowB"];
}

}
protected override object SaveViewState()
{
ViewState["ShowB"] = showB;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
Controls.Clear( );
showtimeA = new ShowTime();
showtimeA.Click +=new EventHandler(sh owtimeA_Click);
Controls.Add(sh owtimeA);

if (showB )
{
showtimeB = new ShowTime();
Controls.Add(sh owtimeB);
}
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
showtimeA.Rende rControl(writer );
if (showB) showtimeB.Rende rControl(writer );
}

public ContainTime()
{

}

private void showtimeA_Click (object sender, EventArgs e)
{
this.showB = !showB;
this.ChildContr olsCreated = false; // if I dont do this, the control is
there
// its the above line that makes the viewstate vanish, but I need it to
cause the controls to dynamicly add.
}
}

/// <summary>
/// Summary description for ShowTime.
/// </summary>
public class ShowTime : WebControl,INam ingContainer
{
public ShowTime()
{
}

string timestring;
Button abutton;
Button getTimeButton;
Button doRoundTrip;

Label timelabel;

public event EventHandler Click;

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
System.Diagnost ics.Trace.Write Line("Items in viewstate " +
ViewState.Count );

if (ViewState["time"] == null)
{
timestring = "Not found";
}
else
{
timestring = (string) ViewState["time"];
}
}
protected override object SaveViewState()
{
ViewState["time"] = timestring;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
// For this example we could just write the time out in the render, but I
need to mimic the class
// that I am having problems with as much as possable.
Controls.Clear( );
timelabel = new Label();
timelabel.Text = timestring;
abutton = new Button();
abutton.Text = "Raise Event";
abutton.Click+= new System.EventHan dler(abutton_Cl ick);

getTimeButton = new Button();
getTimeButton.T ext = "Get Current Time";
getTimeButton.C lick+=new EventHandler(ge tTimeButton_Cli ck);

doRoundTrip = new Button();
doRoundTrip.Tex t = "Do Post Back";
doRoundTrip.Cli ck+=new EventHandler(do RoundTrip_Click );

Controls.Add(ti melabel);
Controls.Add(ab utton);
Controls.Add(ge tTimeButton);
Controls.Add(do RoundTrip);
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
writer.RenderBe ginTag("DIV");
writer.Write(th is.UniqueID);
EnsureChildCont rols();
timelabel.Rende rControl(writer );
abutton.RenderC ontrol(writer);
getTimeButton.R enderControl(wr iter);
writer.Write("T ime of post back " + System.DateTime .Now.ToString() );
doRoundTrip.Ren derControl(writ er);
writer.RenderEn dTag();
}

private void abutton_Click(o bject sender, System.EventArg s e)
{
Click(this,e);
}

private void getTimeButton_C lick(object sender, EventArgs e)
{
this.timestring = System.DateTime .Now.ToString() ;
ChildControlsCr eated=false;
}

private void doRoundTrip_Cli ck(object sender, EventArgs e)
{
System.Diagnost ics.Trace.Write Line("Round trip");
ChildControlsCr eated=false;
}
}
}
CODE BEHIND CODE

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace ViewStateTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected ViewStateTest.C ontainTime ContainTime1;

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}
ASPX PAGE :
<%@ Register TagPrefix="cc1" Namespace="View StateTest"
Assembly="ViewS tateTest" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs" AutoEventWireup ="false"
Inherits="ViewS tateTest.WebFor m1" smartNavigation ="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<cc1:ContainTim e id="ContainTime 1" style="Z-INDEX: 101; LEFT: 56px;
POSITION: absolute; TOP: 48px"
runat="server"> </cc1:ContainTime >
</form>
</body>
</HTML>



Nov 18 '05 #1
3 2632
Dynamicaly added controls are "lost" on each request. They
do actually save their viewstate to the page but on the
next submit they do not read/load it because they're lost,
they dont exist during LoadViewState because you probably
create them later in the page lifecycle like in an
eventhanlder or in Page_Load.

In order for this to work you have to somehow add your
dynamic controls before ViewState is loaded for example in
Page_Init, but another problem arises from this. Let's say
you create some controls and save in your UserControls
ViewState that these controls are created. How to know
which controls you have created since you can't read your
own ViewState in Page_Init? That means you should probably
override the LoadViewState method. I did something like
this I think(!), it was pretty simple and I think it
worked. I overrided LoadViewState. In LoadViewState I
called base.LoadViewSt ate() checked the ViewState to see
which controls I have created, added/created them again
and called base.LoadViewSt ate() with the child controls
created again :) I'm not sure it's the best solution or
that even it will work properly but I hope this helped you
understand the problem...

Sometimes it is much more simple to keep your controls
static and invisible than bother with this though..

-----Original Message-----
All,

I have a CONTROL that contains 1 control (Control ONE), the 1 control thatit can contain 1 or 2 control (Control A and B).

Control A, raises and event and Control ONE receives this event and thiscauses control B to be created, when this is done the VIEWSTATE is lost forCONTROL B.

In the EVENT that causes CONTROL B to be created I have to setChildControlsC reated to false, if I don't set it the viewstate works but thecontrol doesn't show, as the createchild controls does not get re-ran.
Below is the a smaller version of the code that I have created to reproducethe problem test as follows :

Click Get Current Time, it will now show the time
Click do post back, it will still show time in first step, as well as timeof post back, to prove its posted back.
Click Raise Event, it has now lost the viewstate, time has gone blank.Click Get Current Time on both line, you will see the time get filled in andit persisted in the viewstate, do a few clicks to prove this.Now Click Raise Event, view state has been lost again.

Cheers

Steve

Project name should be ViewStateTest

Code : (Add to single class called controls.cs)

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ViewStateTest
{
public class ContainTime : WebControl ,INamingContain er
{
ShowTime showtimeA;
ShowTime showtimeB;

WebControl holdingcontrol;

bool showB;

protected override void LoadViewState(o bject savedState)
{

base.LoadViewSt ate (savedState);
if (ViewState["ShowB"] == null)
{
showB = false;
}
else
{
showB = (bool) ViewState["ShowB"];
}

}
protected override object SaveViewState()
{
ViewState["ShowB"] = showB;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
Controls.Clear( );
showtimeA = new ShowTime();
showtimeA.Click +=new EventHandler(sh owtimeA_Click);
Controls.Add(sh owtimeA);

if (showB )
{
showtimeB = new ShowTime();
Controls.Add(sh owtimeB);
}
}
protected override void Render (System.Web.UI. HtmlTextWriter writer) {
showtimeA.Rende rControl(writer );
if (showB) showtimeB.Rende rControl(writer );
}

public ContainTime()
{

}

private void showtimeA_Click (object sender, EventArgs e)
{
this.showB = !showB;
this.ChildContr olsCreated = false; // if I dont do this, the control isthere
// its the above line that makes the viewstate vanish, but I need it tocause the controls to dynamicly add.
}
}

/// <summary>
/// Summary description for ShowTime.
/// </summary>
public class ShowTime : WebControl,INam ingContainer
{
public ShowTime()
{
}

string timestring;
Button abutton;
Button getTimeButton;
Button doRoundTrip;

Label timelabel;

public event EventHandler Click;

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
System.Diagnost ics.Trace.Write Line("Items in viewstate " +ViewState.Coun t);

if (ViewState["time"] == null)
{
timestring = "Not found";
}
else
{
timestring = (string) ViewState["time"];
}
}
protected override object SaveViewState()
{
ViewState["time"] = timestring;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
// For this example we could just write the time out in the render, but Ineed to mimic the class
// that I am having problems with as much as possable.
Controls.Clear( );
timelabel = new Label();
timelabel.Text = timestring;
abutton = new Button();
abutton.Text = "Raise Event";
abutton.Click+= new System.EventHan dler(abutton_Cl ick);

getTimeButton = new Button();
getTimeButton.T ext = "Get Current Time";
getTimeButton.C lick+=new EventHandler (getTimeButton_ Click);
doRoundTrip = new Button();
doRoundTrip.Tex t = "Do Post Back";
doRoundTrip.Cli ck+=new EventHandler(do RoundTrip_Click );

Controls.Add(ti melabel);
Controls.Add(ab utton);
Controls.Add(ge tTimeButton);
Controls.Add(do RoundTrip);
}
protected override void Render (System.Web.UI. HtmlTextWriter writer) {
writer.RenderBe ginTag("DIV");
writer.Write(th is.UniqueID);
EnsureChildCont rols();
timelabel.Rende rControl(writer );
abutton.RenderC ontrol(writer);
getTimeButton.R enderControl(wr iter);
writer.Write("T ime of post back " + System.DateTime .Now.ToString() ); doRoundTrip.Ren derControl(writ er);
writer.RenderEn dTag();
}

private void abutton_Click(o bject sender, System.EventArg s e) {
Click(this,e);
}

private void getTimeButton_C lick(object sender, EventArgs e) {
this.timestring = System.DateTime .Now.ToString() ;
ChildControlsCr eated=false;
}

private void doRoundTrip_Cli ck(object sender, EventArgs e) {
System.Diagnost ics.Trace.Write Line("Round trip");
ChildControlsCr eated=false;
}
}
}
CODE BEHIND CODE

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace ViewStateTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected ViewStateTest.C ontainTime ContainTime1;

private void Page_Load(objec t sender, System.EventArg s e) {
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer. //
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}
ASPX PAGE :
<%@ Register TagPrefix="cc1" Namespace="View StateTest"
Assembly="View StateTest" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs" AutoEventWireup ="false"Inherits="View StateTest.WebFo rm1" smartNavigation ="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1"> <meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript"> <meta name="vs_target Schema"
content="htt p://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<cc1:ContainTim e id="ContainTime 1" style="Z-INDEX: 101; LEFT: 56px;POSITION: absolute; TOP: 48px"
runat="server"> </cc1:ContainTime >
</form>
</body>
</HTML>



.

Nov 18 '05 #2
These are purely done in server controls, they are created in the correct
order ect and the viewstates does work, but .... the viewstats gets zapped
when a control is added.

This is how my controls are laid out (this looks fine in OE with default
font, if it don't look OK cut and paste the NOTEPAD version at the end.

*************** *************** ***
* PAGE *
* *
* *************** ************* *
* * CONTROL ONE * *
* * * *
* * *************** * * *
* * * CONTROL A * * *
* * * [BUTTON] * * *
* * *************** * * *
* * * *
* * *************** * * *
* * * CONTROL B * * *
* * * [BUTTON] * * *
* * *************** * * *
* *************** ************* *
*************** *************** ***

Control B is not created at the start, I click the button on A, CONTROL A
raises an event, CONTROL process the event and stores a flag in the
viewstate to tell CONTROL ONE to create a CONTROL B (this flag keeps its
viewstate ok) , and it creates control B, but control A loses its viewstate
(ONLY CONTROL A) , i then click the button in control B, this does a post
back on all control keep there viewstate.

A work around is to store the viewstat for CONTROL A and B in CONTROL ONE,
this does work, but is going to be tricky todo in other server controls.

I am starting to think that this is just the way it works, you need to test
the code yourself to see the problem.

NOTEPAD VERSION (cut and paste me into notepad)

---- start cut ----
*************** *************** ***
* PAGE *
* *
* *************** ************ *
* * CONTROL ONE * *
* * * *
* * *************** * * *
* * * CONTROL A * * *
* * * [BUTTON] * * *
* * *************** * * *
* * * *
* * *************** * * *
* * * CONTROL B * * *
* * * [BUTTON] * * *
* * *************** * * *
* *************** ************ *
*************** *************** ***
---- end cut ----
"Adrijan Josic" <ad*****@vidpat a.hr> wrote in message
news:09******** *************** *****@phx.gbl.. .
Dynamicaly added controls are "lost" on each request. They
do actually save their viewstate to the page but on the
next submit they do not read/load it because they're lost,
they dont exist during LoadViewState because you probably
create them later in the page lifecycle like in an
eventhanlder or in Page_Load.

In order for this to work you have to somehow add your
dynamic controls before ViewState is loaded for example in
Page_Init, but another problem arises from this. Let's say
you create some controls and save in your UserControls
ViewState that these controls are created. How to know
which controls you have created since you can't read your
own ViewState in Page_Init? That means you should probably
override the LoadViewState method. I did something like
this I think(!), it was pretty simple and I think it
worked. I overrided LoadViewState. In LoadViewState I
called base.LoadViewSt ate() checked the ViewState to see
which controls I have created, added/created them again
and called base.LoadViewSt ate() with the child controls
created again :) I'm not sure it's the best solution or
that even it will work properly but I hope this helped you
understand the problem...

Sometimes it is much more simple to keep your controls
static and invisible than bother with this though..

-----Original Message-----
All,

I have a CONTROL that contains 1 control (Control ONE),

the 1 control that
it can contain 1 or 2 control (Control A and B).

Control A, raises and event and Control ONE receives this

event and this
causes control B to be created, when this is done the

VIEWSTATE is lost for
CONTROL B.

In the EVENT that causes CONTROL B to be created I have

to set
ChildControlsC reated to false, if I don't set it the

viewstate works but the
control doesn't show, as the createchild controls does

not get re-ran.

Below is the a smaller version of the code that I have

created to reproduce
the problem test as follows :

Click Get Current Time, it will now show the time
Click do post back, it will still show time in first

step, as well as time
of post back, to prove its posted back.
Click Raise Event, it has now lost the viewstate, time

has gone blank.
Click Get Current Time on both line, you will see the

time get filled in and
it persisted in the viewstate, do a few clicks to prove

this.
Now Click Raise Event, view state has been lost again.

Cheers

Steve

Project name should be ViewStateTest

Code : (Add to single class called controls.cs)

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ViewStateTest
{
public class ContainTime : WebControl ,INamingContain er
{
ShowTime showtimeA;
ShowTime showtimeB;

WebControl holdingcontrol;

bool showB;

protected override void LoadViewState(o bject savedState)
{

base.LoadViewSt ate (savedState);
if (ViewState["ShowB"] == null)
{
showB = false;
}
else
{
showB = (bool) ViewState["ShowB"];
}

}
protected override object SaveViewState()
{
ViewState["ShowB"] = showB;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
Controls.Clear( );
showtimeA = new ShowTime();
showtimeA.Click +=new EventHandler(sh owtimeA_Click);
Controls.Add(sh owtimeA);

if (showB )
{
showtimeB = new ShowTime();
Controls.Add(sh owtimeB);
}
}
protected override void Render

(System.Web.UI. HtmlTextWriter writer)
{
showtimeA.Rende rControl(writer );
if (showB) showtimeB.Rende rControl(writer );
}

public ContainTime()
{

}

private void showtimeA_Click (object sender, EventArgs e)
{
this.showB = !showB;
this.ChildContr olsCreated = false; // if I dont do

this, the control is
there
// its the above line that makes the viewstate vanish,

but I need it to
cause the controls to dynamicly add.
}
}

/// <summary>
/// Summary description for ShowTime.
/// </summary>
public class ShowTime : WebControl,INam ingContainer
{
public ShowTime()
{
}

string timestring;
Button abutton;
Button getTimeButton;
Button doRoundTrip;

Label timelabel;

public event EventHandler Click;

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
System.Diagnost ics.Trace.Write Line("Items in

viewstate " +
ViewState.Coun t);

if (ViewState["time"] == null)
{
timestring = "Not found";
}
else
{
timestring = (string) ViewState["time"];
}
}
protected override object SaveViewState()
{
ViewState["time"] = timestring;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
// For this example we could just write the time out

in the render, but I
need to mimic the class
// that I am having problems with as much as possable.
Controls.Clear( );
timelabel = new Label();
timelabel.Text = timestring;
abutton = new Button();
abutton.Text = "Raise Event";
abutton.Click+= new System.EventHan dler(abutton_Cl ick);

getTimeButton = new Button();
getTimeButton.T ext = "Get Current Time";
getTimeButton.C lick+=new EventHandler

(getTimeButton_ Click);

doRoundTrip = new Button();
doRoundTrip.Tex t = "Do Post Back";
doRoundTrip.Cli ck+=new EventHandler(do RoundTrip_Click );

Controls.Add(ti melabel);
Controls.Add(ab utton);
Controls.Add(ge tTimeButton);
Controls.Add(do RoundTrip);
}
protected override void Render

(System.Web.UI. HtmlTextWriter writer)
{
writer.RenderBe ginTag("DIV");
writer.Write(th is.UniqueID);
EnsureChildCont rols();
timelabel.Rende rControl(writer );
abutton.RenderC ontrol(writer);
getTimeButton.R enderControl(wr iter);
writer.Write("T ime of post back " +

System.DateTime .Now.ToString() );
doRoundTrip.Ren derControl(writ er);
writer.RenderEn dTag();
}

private void abutton_Click(o bject sender,

System.EventArg s e)
{
Click(this,e);
}

private void getTimeButton_C lick(object sender,

EventArgs e)
{
this.timestring = System.DateTime .Now.ToString() ;
ChildControlsCr eated=false;
}

private void doRoundTrip_Cli ck(object sender, EventArgs

e)
{
System.Diagnost ics.Trace.Write Line("Round trip");
ChildControlsCr eated=false;
}
}
}
CODE BEHIND CODE

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace ViewStateTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected ViewStateTest.C ontainTime ContainTime1;

private void Page_Load(objec t sender, System.EventArg s

e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web

Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}
ASPX PAGE :
<%@ Register TagPrefix="cc1" Namespace="View StateTest"
Assembly="View StateTest" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"

AutoEventWireup ="false"
Inherits="View StateTest.WebFo rm1" smartNavigation ="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual

Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript"

content="JavaSc ript">
<meta name="vs_target Schema"
content="htt p://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<cc1:ContainTim e id="ContainTime 1" style="Z-INDEX:

101; LEFT: 56px;
POSITION: absolute; TOP: 48px"
runat="server"> </cc1:ContainTime >
</form>
</body>
</HTML>



.

Nov 18 '05 #3
I fixed this as follows (note new BASE CLASS), comments welcome:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ViewStateTest
{
public class myControl : WebControl
{
internal object mySaveViewState ()
{
return this.SaveViewSt ate ();
}
internal void myLoadViewState (object savedState)
{
this.LoadViewSt ate (savedState);
}
internal void myTrackViewStat e()
{
this.TrackViewS tate();
}
}

public class ContainTime : myControl,INami ngContainer
{

showtime showtimeA=new showtime();
showtime showtimeB=new showtime();

System.Web.UI.W ebControls.Cale ndar calA;
System.Web.UI.W ebControls.Cale ndar calB;

WebControl holdingcontrol;

bool showB;

protected override void LoadViewState(o bject savedState)
{
if (savedState!=nu ll)
{
object[] states = (object[]) savedState;

if(states[0] != null)
base.LoadViewSt ate(states[0]);
if(states[1] != null)
showtimeA.myLoa dViewState(stat es[1]);
if(states[2] != null)
showtimeB.myLoa dViewState(stat es[2]);
}

/* Load Custom View State here */
object o = ViewState["ShowB"] ;
if (o== null)
showB = false;
else
showB = (bool) o;

}
protected override object SaveViewState()
{

ViewState["ShowB"] = showB;

object[] states = new object [3];
states[0] = base.SaveViewSt ate();
states[1] = (showtimeA== null ? null : showtimeA.mySav eViewState());
states[2] = (showtimeB== null ? null : showtimeB.mySav eViewState());
for(int i=0; i < states.Length; i++)
{
if(states[i]!=null)
return states;
}
return null;
}
protected override void CreateChildCont rols()
{
Controls.Clear( );
showtimeA.ID = "SA";
showtimeB.ID = "SB";

showtimeA.Click +=new EventHandler(sh owtimeA_Click);
Controls.Add(sh owtimeA);
calA = new Calendar();
Controls.Add(ca lA);

// if (showB )
{
calB = new Calendar();
Controls.Add(sh owtimeB);
Controls.Add(ca lB);
}
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
showtimeA.Rende rControl(writer );
calA.RenderCont rol(writer);
if (showB) showtimeB.Rende rControl(writer );
if (showB) calB.RenderCont rol(writer);
}
protected override void TrackViewState( )
{
base.TrackViewS tate ();
}

public ContainTime()
{
showtimeA=new showtime();
showtimeB=new showtime();

}

private void showtimeA_Click (object sender, EventArgs e)
{
this.showB = !showB;
this.ChildContr olsCreated = false;
}
}

/// <summary>
/// Summary description for showtime.
/// </summary>
public class showtime : myControl,INami ngContainer
{
public showtime()
{
}

string timestring;
Button abutton;
Button getTimeButton;
Button doRoundTrip;

Label timelabel;

public event EventHandler Click;

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
System.Diagnost ics.Trace.Write Line("Items in viewstate " +
ViewState.Count );

if (ViewState["time"] == null)
{
timestring = "Not found";
}
else
{
timestring = (string) ViewState["time"];
}
}
protected override object SaveViewState()
{
ViewState["time"] = timestring;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
// For this example we could just write the time out in the render, but I
need to mimic the class
// that I am having problems with as much as possable.
Controls.Clear( );
timelabel = new Label();
timelabel.Text = timestring;
abutton = new Button();
abutton.Text = "Raise Event";
abutton.Click+= new System.EventHan dler(abutton_Cl ick);

getTimeButton = new Button();
getTimeButton.T ext = "Get Current Time";
getTimeButton.C lick+=new EventHandler(ge tTimeButton_Cli ck);

doRoundTrip = new Button();
doRoundTrip.Tex t = "Do Post Back";
doRoundTrip.Cli ck+=new EventHandler(do RoundTrip_Click );

Controls.Add(ti melabel);
Controls.Add(ab utton);
Controls.Add(ge tTimeButton);
Controls.Add(do RoundTrip);
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
writer.RenderBe ginTag("DIV");
writer.Write(th is.UniqueID);
EnsureChildCont rols();
timelabel.Rende rControl(writer );
abutton.RenderC ontrol(writer);
getTimeButton.R enderControl(wr iter);
writer.Write("T ime of post back " + System.DateTime .Now.ToString() );
doRoundTrip.Ren derControl(writ er);
writer.RenderEn dTag();
}

private void abutton_Click(o bject sender, System.EventArg s e)
{
base.TrackViewS tate ();

Click(this,e);
}

private void getTimeButton_C lick(object sender, EventArgs e)
{
this.timestring = System.DateTime .Now.ToString() ;
ChildControlsCr eated=false;
}

private void doRoundTrip_Cli ck(object sender, EventArgs e)
{
System.Diagnost ics.Trace.Write Line("Round trip");
ChildControlsCr eated=false;
}
}
}

"Steve Drake" <Steve@_NOSPAM_ Drakey.co.uk> wrote in message
news:e1******** ******@TK2MSFTN GP09.phx.gbl...
All,

I have a CONTROL that contains 1 control (Control ONE), the 1 control that
it can contain 1 or 2 control (Control A and B).

Control A, raises and event and Control ONE receives this event and this
causes control B to be created, when this is done the VIEWSTATE is lost for CONTROL B.

In the EVENT that causes CONTROL B to be created I have to set
ChildControlsCr eated to false, if I don't set it the viewstate works but the control doesn't show, as the createchild controls does not get re-ran.

Below is the a smaller version of the code that I have created to reproduce the problem test as follows :

Click Get Current Time, it will now show the time
Click do post back, it will still show time in first step, as well as time
of post back, to prove its posted back.
Click Raise Event, it has now lost the viewstate, time has gone blank.
Click Get Current Time on both line, you will see the time get filled in and it persisted in the viewstate, do a few clicks to prove this.
Now Click Raise Event, view state has been lost again.

Cheers

Steve

Project name should be ViewStateTest

Code : (Add to single class called controls.cs)

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ViewStateTest
{
public class ContainTime : WebControl ,INamingContain er
{
ShowTime showtimeA;
ShowTime showtimeB;

WebControl holdingcontrol;

bool showB;

protected override void LoadViewState(o bject savedState)
{

base.LoadViewSt ate (savedState);
if (ViewState["ShowB"] == null)
{
showB = false;
}
else
{
showB = (bool) ViewState["ShowB"];
}

}
protected override object SaveViewState()
{
ViewState["ShowB"] = showB;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
Controls.Clear( );
showtimeA = new ShowTime();
showtimeA.Click +=new EventHandler(sh owtimeA_Click);
Controls.Add(sh owtimeA);

if (showB )
{
showtimeB = new ShowTime();
Controls.Add(sh owtimeB);
}
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
showtimeA.Rende rControl(writer );
if (showB) showtimeB.Rende rControl(writer );
}

public ContainTime()
{

}

private void showtimeA_Click (object sender, EventArgs e)
{
this.showB = !showB;
this.ChildContr olsCreated = false; // if I dont do this, the control is
there
// its the above line that makes the viewstate vanish, but I need it to
cause the controls to dynamicly add.
}
}

/// <summary>
/// Summary description for ShowTime.
/// </summary>
public class ShowTime : WebControl,INam ingContainer
{
public ShowTime()
{
}

string timestring;
Button abutton;
Button getTimeButton;
Button doRoundTrip;

Label timelabel;

public event EventHandler Click;

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
System.Diagnost ics.Trace.Write Line("Items in viewstate " +
ViewState.Count );

if (ViewState["time"] == null)
{
timestring = "Not found";
}
else
{
timestring = (string) ViewState["time"];
}
}
protected override object SaveViewState()
{
ViewState["time"] = timestring;
return base.SaveViewSt ate ();
}

protected override void CreateChildCont rols()
{
// For this example we could just write the time out in the render, but I need to mimic the class
// that I am having problems with as much as possable.
Controls.Clear( );
timelabel = new Label();
timelabel.Text = timestring;
abutton = new Button();
abutton.Text = "Raise Event";
abutton.Click+= new System.EventHan dler(abutton_Cl ick);

getTimeButton = new Button();
getTimeButton.T ext = "Get Current Time";
getTimeButton.C lick+=new EventHandler(ge tTimeButton_Cli ck);

doRoundTrip = new Button();
doRoundTrip.Tex t = "Do Post Back";
doRoundTrip.Cli ck+=new EventHandler(do RoundTrip_Click );

Controls.Add(ti melabel);
Controls.Add(ab utton);
Controls.Add(ge tTimeButton);
Controls.Add(do RoundTrip);
}
protected override void Render(System.W eb.UI.HtmlTextW riter writer)
{
writer.RenderBe ginTag("DIV");
writer.Write(th is.UniqueID);
EnsureChildCont rols();
timelabel.Rende rControl(writer );
abutton.RenderC ontrol(writer);
getTimeButton.R enderControl(wr iter);
writer.Write("T ime of post back " + System.DateTime .Now.ToString() );
doRoundTrip.Ren derControl(writ er);
writer.RenderEn dTag();
}

private void abutton_Click(o bject sender, System.EventArg s e)
{
Click(this,e);
}

private void getTimeButton_C lick(object sender, EventArgs e)
{
this.timestring = System.DateTime .Now.ToString() ;
ChildControlsCr eated=false;
}

private void doRoundTrip_Cli ck(object sender, EventArgs e)
{
System.Diagnost ics.Trace.Write Line("Round trip");
ChildControlsCr eated=false;
}
}
}
CODE BEHIND CODE

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace ViewStateTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected ViewStateTest.C ontainTime ContainTime1;

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}
ASPX PAGE :
<%@ Register TagPrefix="cc1" Namespace="View StateTest"
Assembly="ViewS tateTest" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs" AutoEventWireup ="false" Inherits="ViewS tateTest.WebFor m1" smartNavigation ="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<cc1:ContainTim e id="ContainTime 1" style="Z-INDEX: 101; LEFT: 56px;
POSITION: absolute; TOP: 48px"
runat="server"> </cc1:ContainTime >
</form>
</body>
</HTML>


Nov 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4876
by: theo | last post by:
Hi... I wish to extract the text content of an Xml file and assign it to DropDownList controls at runtime.I can get the Xml file text content into the DropDownList controls (Ex...if 5 Xml text tags then 5 dropdownlist controls each containing the 5 Xml text tags). Problem,when I save the user DropDownList selected items by means of a...
9
21630
by: John Kirksey | last post by:
I have a page that uses an in-place editable DataGrid that supports sorting and paging. EnableViewState is turned ON. At the top of the page are several search fields that allow the user to filter the results in the grid. Say you filter the grid for records that have a certain condition set to "NO" (in this case a checkbox). In this scenario...
10
2243
by: neo | last post by:
hi, I am studying ASP.NET and have few questions - 1) The session ID and values of controls is stored in VIEWSTATE variable. So now when we put EnableViewState="false" in Page directive and disable the session state in Web.Config the VIEWSTATE variable is still maintained and stores some values. Can anyone tell what those values are for,...
8
4265
by: Invalidlastname | last post by:
Hi, We are developing an asp.net application, and we dynamically created certain literal controls to represent some read-only text for certain editable controls. However, recently we found an issue which is related to the repeater. In the code shown below, if I call Repeater1.Controls.Count in the OnInit (the code fragment was highlighted in...
4
6719
by: Chuck Ritzke | last post by:
Hi, I've searched the newsgroup and other sources to understand how to handle runtime controls and see I'm not the only one who's confused, but I'm still not quite sure of the best way to handle from all the various explanations/answers. I'm attempting the typical scenario... I create a variable number of controls at runtime based on...
6
2058
by: hitendra15 | last post by:
Hi I have created web user control which has Repeater control and Linkbutton in ItemTemplate of repeater control, following is the code for this control On first load it runs fine but when page gets post back it gives following error Failed to load viewstate. The control tree into which viewstate is
1
1650
by: Christophe Peillet | last post by:
I have a CompositeControl with two types of properties: 1.) Mapped Properties that map directly to a child control's properties (ex.: this.TextboxText = m_txt.Text). These properties are handled by their underlying classes (such as the TextBox control), and are not persisted by me. 2.) Unique Properties that don't map directly and are...
6
4403
by: Peter Zolja | last post by:
Hi, I'm building a webcontrol that contains a dynamic list of other controls. My problem is that when I add or remove an item the synchronization between the ViewState and the Controls collection seems to break -- or at least that's my theory for now. Here's what I do; to add an item I do that following on the PostBack of a button: 1....
12
1899
by: Nick C | last post by:
Hi How can i reduce the viewstate for my asp.net application. It is getting very large now. What is a good solution? thanks N
0
7408
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7590
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7688
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5271
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4895
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3391
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3391
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
968
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.