Viewstate of WebUserControl does NOT work

  • Thread starter Thread starter Christian
  • Start date Start date
C

Christian

Hi,

Viewstate of WebUserControl does NOT work although the
'EnableViewstate'-property of the usercontrol is set to true

Description :

Using ASP.Net :
I have a created a WebPage with 2 buttons and 1 Web-UserControl of type
LottoWebUserControl. The control has 1 label-control embedded

The purpose is to toggle the visible-property of the embedded-label-ctrl
using the 2 buttons:

Some sample code :

public class LottoWebUserControl : System.Web.UI.UserControl
{
private void Page_Load(object sender, System.EventArgs e)
{
if ( ! IsPostBack )
MyVisible = false;
else
MyVisbile = (bool)ViewState["visible"];
}
public bool MyVisible
{
get { return (bool)ViewState["visible"]; }
set
{
ViewState["visible"] = value;
SetState();
}
}
private void SetState()
{
lbl1.Visible = (bool)ViewState["visible"];
}
}

// The Web-Page containing the 2 buttons and an instance of the usercontrol
// 'EnableViewstate'-property of the usercontrol is set to true
public class WebForm1 : System.Web.UI.Page
{
protected LottoWebUserControl m_LottoWebUserControl = new
LottoWebUserControl();

private void button1_Click(object sender, System.EventArgs e)
{
m_LottoWebUserControl.MyVisible = true;
}
private void button2_Click(object sender, System.EventArgs e)
{
m_LottoWebUserControl.MyVisible = false;
}
}

The toggling does NOT work. The label-ctrl remains in one state.

Maybe a clue : ViewState["visible"] has a correct value when used in the
Page_Load() handler but when accessed in the set-part of MyVisible-property
has it a value of null (before ViewState["visible"] = value; is executed)

any ideas ?
thanks

Chris
 
Make sure that you are setting the property for your control in the
PreRender events of your page. If you do it in the actual page load event of
the containing page it's too late.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage
 
Mark Fitzpatrick wrote :
"Make sure that you are setting the property for your control in the
PreRender events of your page. If you do it in the actual page load
event of the containing page it's too late."


I'm quite new to ASP.Net so I'll have to ask you how to do it. I mean :
according to the specific button I click (button1 or button2) do I set
my property, so who do I 'map' that code in the PreRender event ?

--> original code
private void button1_Click(object sender, System.EventArgs e)
{
m_LottoWebUserControl.MyVisible = true;
}
private void button2_Click(object sender, System.EventArgs e)
{
m_LottoWebUserControl.MyVisible = false;
}
 
Back
Top