Button.Visible = false ?

  • Thread starter Thread starter Marc Lefebvre
  • Start date Start date
M

Marc Lefebvre

Why I was unable to hide the previous button in the following code ?


private void ButtonClick(Object sender, System.EventArgs e)
{
Button button = (Button)sender;
Button previousButton = (Button)Session["previousButton"];

if( previousButton == null )
{
// keep the first button
previousButton = button;
Session["previousButton"] = previousButton;
}
else
{
// Hide both button
button.Visible = false;
previousButton.Visible = false; // E R R O R don't work
previousButton = null;
Session["previousButton"] = previousButton;
}
}

Thank's

Marc
 
You simply cannot store a button in the Session. Don't forget that when the
page will be posted back, a NEW button will be created for any button
control on the page; so if you save a button, and on the next postback set
it to invisible, it will no be the button that exists on the page generated
by the postback.

To solve this problem, I suggest that you store the control's ID in the
ViewState, and then use FindControl to find it.

Your code would look like this:
private void ButtonClick(Object sender, System.EventArgs e)
{
Button button = (Button)sender;
Button previousButton = (Button)FindControl[(string)Session["previousButton"]];

if( previousButton == null )
{
// keep the first button
previousButton = button;
Session["previousButton"] = previousButton.ID;
}
else
{
// Hide both button
button.Visible = false;
previousButton.Visible = false;
}
}
 
Back
Top