Button_Click and Session

  • Thread starter Thread starter Marine
  • Start date Start date
M

Marine

Hi,

Sorry i'm a newbie with Asp.net, here is my problem :

private void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack) { Label1.Text = (string)Session["test"]; }
}

private void Button1_Click(object sender, System.EventArgs e)
{
Session["test"] = "test";
}

I have to click two times on the button to see "test".

Thanks for any help.
 
re:
!> I have to click two times on the button to see "test".

try this :

private void Button1_Click(object sender, System.EventArgs e)
{
Session["test"] = "test";
Label1.Text = (string)Session["test"];
}

Or...you can try this :

private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = (string)Session["test"];
}






Juan T. Llibre, asp.net MVP
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en español : http://asp.net.do/foros/
======================================
 
Hi Marine,
Hi,

Sorry i'm a newbie with Asp.net, here is my problem :
I have to click two times on the button to see "test".

The reason is that Page_Load gets executed before Button1_Click, so when
you click the button for the first time, Page_Load sets the label to an
(empty) session variable and only after that the session variable is set
to the string "test".

As Juan has shown, you can set the label text in the click event
directly and don't need to do that in Page_Load at all.

Hope this helps,

Roland
 
John said:
change the
if (IsPostBack)

to

if (!IsPostBack)

:)

That will have the opposite effect of the wanted. With your suggested
chage, the text will never change.
 
Oops, misread the intention, sorry...

Button_Click gets handled after the page_load, hence the label get's
set to early... Setting the label in the Button_Click should help...
but that was posted as an option earlier this thread :-)
 
Hi,

Sorry i'm a newbie with Asp.net, here is my problem :

private void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack) { Label1.Text = (string)Session["test"]; }
}

private void Button1_Click(object sender, System.EventArgs e)
{
Session["test"] = "test";
}

I have to click two times on the button to see "test".

Thanks for any help.

And a suggestion I've not yet seen in this thread:
move the "label setting" from Page_Load to Page_PreRender, which is
called *after* the click has been handled.

Hans Kesting
 
Back
Top