Button_Click and Session

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.
 
J

Juan T. Llibre

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"];
}
 
R

Roland Dick

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 
J

John MJ Gorter

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 :)
 
H

Hans Kesting

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top