Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple event firing in a web form

Status
Not open for further replies.

goatstudio

Programmer
Nov 25, 2001
75
SG
Hi all,

I have a web form, and my page is coded in c#.
There is a button and a label in my webform, when I click on the button, the label should display +1.

My code as below:

protected void Button_Submit_OnClick (Object Src, EventArgs E) {
Label1.Text = "Total: " + (x++);
}

x is public variable in the page. The problem is this event only fire at the first time...and seems not firing at all at the second time.

Any clue? :)

Thanks!

regards,
vic

------------------
Freedom is a Right
 
the event is not fired at all or the value is not increased? set a breakpoint on your Label1.Text = ... and see if it executes the instruction.

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
The web form applications are implemented using a single call remoting object e.g. every call made to the the web form creates an object on the remote machine (named as your web form),executes the method on that objects e.g. Button_Submit_OnClick (), sends back the response to the client (your browser) and the remote object is destroyed.
For the next call of Button_Submit_OnClick () a new object is created again and there is nothing stored about the previous remote object, so this is the reason you never see x incremented.
Even if you declare it as static, you will see the same result because the x variable starts every time with the initial value.
The x++; statement is executed but the object form is destroyed after the page is displayed back.
So, for the web form application, which are known as stateless, there is the Session object in which you can store the states of the objects during the whole session and shared betweens forms.
Here is one example how to modify your code to get x variable incremented:
Code:
private void Page_Load(object sender, System.EventArgs e)
{


	if (Session["myX"]==null)
		Session.Add("myX", 0);
}

private void Button1_Click(object sender, System.EventArgs e)
{
	if (Session["myX"] != null)
	{
		Session["myX"]=(int)Session["myX"] + 1;
		this.Label1.Text = "Total: " + Session["myX"];
	}

}
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top