Button CLick Event + Page Load Event ( Why does Page load clear all my variables )

super asp noob here ---and i hve to get this done asap --- thxn everyone for reading and responding

heres my program in psuedo code

page load ()





public make_ table ()


make a table - read data from a database- set  data -- store lots of data in arrays and variables



button1_click ()





public get_data()


get all  the data from the variables--

read from the  table--+ all the variables

store the data



 basically the user can enter in data  into the text boxes embedded as controls on each cell of the table

i want to read that data and update the database

now when i do teh click butotn- my page load runs ---and CLEARS ALL My variabless


whyy why does it delete all the stuff in my variables..


i want the button click event to run bfore the page load deletes my data--


8/10/2007 5:07:15 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

10 Replies

Similar Articles

[PageSpeed] 20
Get it on Google Play
Get it on Apple App Store

This is a very common issue with newer developers.

 When you do a postback (button click), it goes to the server and hits the Page_Load() first. In your case this loads the Tables, which will eraase the content put into it.

What I would do is this:


page load ()





What this will do is only call make_table() on the first load, as every other postback on this page, will not call make_table as they're postbacks.


Hopefully this helps.

The Killer Ninja Coding Monkeys thank those that mark helpful posts as answers.

My Site | My Examples | My Blog

8/10/2007 5:25:11 PM

Also, you will most likely want to save your table in a session variable, that way when the page reloads and it IS a postback you can add the table to the page's controls.

8/10/2007 5:33:42 PM

thanx - that wud hve helped me to avoid session variables --

but why does my data dissapear---


the first row of the table is hard coded in the aspx page--

so the generate table is actually adding rows ---

sorry for not mentioning this earlier---



so 1 way that i see now is to make teh whole table programically--- and put your code in ---

but i dont want to lose the data that the use has put in those text boxes

rite now the page load event aparantlyy deletes all the data -- and all the rows as well-- on the server side--- but the table is still intact on the user's page (local cache?) ---

dim tempbox as textbox

tempbox = Table1.Rows(i).Cells(1).Controls(0)     ----> this line fails -- with the error message

"Specified argument was out of the range of valid values." 

suggesting that  the row / cell no longer exists.....even tho i had put



-- thnx for the quick response

much appreciated

8/10/2007 5:34:42 PM

If you are using DataBind() to bind your table I would urge you not to use the session to store the data. That is abusing what the session is for. The Table will retains it's information in the ViewState, which will not force you to use server memory.

 If you do bind using:

DataGrid.DataSource = a_DataSource;

your information will be saved in the viewstate so it's easy to work with it. However, if you are using a Table object, that information will not be saved during a postback so you will need to rebind it.

Can you give us more information?


The Killer Ninja Coding Monkeys thank those that mark helpful posts as answers.

My Site | My Examples | My Blog

8/10/2007 5:44:37 PM

you must bind the data to the dataset in the

if not ispostback

in the load event

Known is handful and unknown is worldful.

Ajay Matharu
8/10/2007 5:53:37 PM


it gets a bit complicated ---


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


If Request.QueryString("accountID") = "" Then

addtolog("account id is blank")



If Session("session2") <> "generate is false" Then


Table1.Height = Unit.Pixel((numproducts + 1) * 30)

Session("session2") = "generate is false"

End If

End If



Protected Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Session("session1") = "update is true"

Session("session2") = "generate is true"




End Sub




<script language="javascript">

var loc;

loc= window.location + "";

if (loc.indexOf("accountID")>-1)




{ var arr = new Array(window.dialogArguments.length - 1);

arr = window.dialogArguments;

//window.location.href=loc+"?fundID=" + arr[0];


"?accountID=" + arr[0],"","status=0,toolbar=1,location=0,menubar=1,scrollbars = 1, resizable=1,width=1000,height=700");

//window.location.href=loc+"?fundID=" + "70D9F869-1BEC-DB11-AE6C-00120E533B30";







this is my sequence of events::

open the page using a button in another aspx page---

my page load runs twice bcuz i hve javascript in the aspx source code (look above for js)

anyway--- so my page load runs fine--the first time around--

generate table runs---

the table comes up ---with all the data in the text boxes---

i add cells to rows-- and add a textbox control to each cell -- i dun assign IDs to anything ---

now the user modifies as much data as he wants --- thenn clicks a button ---

then the page load runs again --- this caused me to loose all my data -which i extracted from the database during the first run...

so i run the generate table again to get my database queries again--- but i dont add any rows---

now i run the get data function -- which needs the database query results ++ the user entered data into the text boxes--


but the user  entered data in the textbox is gone ---!!  deleted by the stupid page load---


bottom line is-- i need to get hold of that data in the textboxes bfore it gets deleted by the pageload ---


8/10/2007 6:08:48 PM



i dun care about the data retrieved from teh queries anymore---

its the user entered data in the text boxes thats slipping away---

now the user can change this constantly --- and  when he clicks the button - i want to call the method to capture the textbox data--

but the dumb pageload deletes it  bfore i can do anything


as i said bfore :  the rows + cells + textboxes r dynamically  created when the generate table function runs

the first row is hard coded -- the rest r  added after the database query

8/10/2007 6:13:35 PM

thnx for all the efforts so far

i am swimming in the deep end here -- and i dun knw how to swim!

8/10/2007 6:14:45 PM

i had this working a long time ago ---

at that point i wasnt using session state--

this is the new stuff that i added in as i went thru the project


enableeventvalidation="false" EnableSessionState ="True"  in the aspx page ttag



<pages enableSessionState ="true">              ----- i never had this line


<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>





<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add name="Session" type="System.Web.SessionState.SessionStateModule"/>                       --- > i never had this 



but i need all of them to enable sessiom state --- but i wonder if they r causing the data losss

8/10/2007 6:31:44 PM


heres the solution:


this is wat i WAS doing --


page load()


   if session is X --> generate table()

session is Y



button1 click


    get data from the table


 this cleared all the data from my table--


now wat i am doin is ---


page load()


  generate table()



button1 click


    get data from the table



now in the generate table function -- all the user entered  data is supposedly overwritted-- but its not--- weeiirdd...


Public Sub add_tablerow(ByVal product_name, ByVal row_num)



Dim myrow As New TableRow

Dim mycell1 As New TableCell

mycell1.ID = "box" & row_num & "0"

mycell1.Text = product_name



' addtolog(" add a row stage 1 ")

For y As Integer = 1 To 12 Step 1

Dim mycell As New TableCell

Dim mytextbox As New TextBox

mytextbox.CssClass = "textbox"


mytextbox.CssClass = "textbox"

mytextbox.Width = Unit.Pixel(50)

'Dim mywatermark As New AjaxControlToolkit.TextBoxWatermarkExtender

'mywatermark.ID = "WaterMark" & (((row_num - 1) * 12) + y).ToString

'mywatermark.TargetControlID = mytextbox.ID

'mywatermark.WatermarkText = "No Data"

'mywatermark.WatermarkCssClass = "watermark"

If (monthly_numbers(y - 1) <> 0) Then

mytextbox.Text = monthly_numbers(y - 1)


mytextbox.Text = 0

End If



mycell.ID = "box" & row_num.ToString & " " & y.ToString


' mycell.Controls.Add(mywatermark)

mycell.CssClass = "withbg"




Session("session1") = "update is false"

Catch ex As Exception

addtolog("error in add table row " & ex.Message)

End Try

End Sub




this runs both times --


8/13/2007 4:49:33 PM

Similar Artilces:

Triggering a button click event immediately after page load event is complete
It is possible to trigger a button click event immediately after page load event is complete. I have .net 1.1 web application which retrieves data from an external source and if certain criteria is met, i'd like a button on the page to be "clicked" automatically as soon as the page is rendered. Is this practice common? I'd like to avoid reduplicating code from the botton click event to the page load event.  Why would you do that?? What is the button click doing? Calling clientside code or serverside code? Eric Pascarello.com | Twitter epascarello | LinkedIn Th...

Master Page's Page Load firing twice on events called from other Page events
I have numerous pages tied to my MasterPage that controls 2 Always visible extenders for User Reminders and a Counter. I would like them to only fire on a Page_Load once, not twice. I have read a million posts about AutoEventWireupset to false, but on all my pages it is set to true and on those pages the events only fire once. The Master page is giving me problems on events firing twice. Any suggestions? here is some code... protected void Page_Load(object sender, EventArgs e) {if (!Page.Master.IsPostBack) {  I call 2 stored procedures here that should only fire once on a Page_Lo...

To access a control placed in a web user control which is loaded during page load in button click event
How can I access a control in a web user control in a button click event , the user control is loaded in page load.Thanks & Regards,Abhiram Reddy Mekha. Try checking this... http://microsoft.apress.com/asptodayarchive/73869/event-handling-between-custom-user-controls-that-are-loaded-at-run-time http://aspalliance.com/565_Dynamic_Loading_of_ASPNET_User_Controls http://www.beansoftware.com/ASP.NET-Tutorials/Controls-Run-Time.aspx http://stackoverflow.com/questions/92792/user-control-created-dynamically-not-able-to-handle-events-on-postback http://www.codersource.net/asp_net_user_c...

Error when Loading Dynamic UserControl from current User Control's Button Click event Calling Page Event
Hi,I have a panel that I load user Control in no problem.  The problemarrises when I do a post back on one of these user controls.  I havebutton it does a click event.  In this click event I will do somedatabase updates, then I will use reflection to call a method in theparent (this.page) to load the new user control.  Its at this pointafter it loads the new user control that it throws the error "Thecontrol must be placed inside a form tag with runat=server".Now, my methods that managers the user control works.  I am able toclick on the parent page menu and...

when i click submit button,then this page close and new page open.Problem is that after submit button click page take too much time to close.i want to put something like page loading image after "subm
when i click submit button,then this page close and new page open.Problem is that after submit button click page take too much time to close.i want to put something like page loading image after "submit button" click & i want to display this loading image till page will be close. please help...... Dim strscript As String strscript = "" strscript &= "window.close();" strscript &= "window.opener.location.reload();" strscript &= "" 'Literal1.Text = strscrip...

3.5 Beta- when I click on the home page button-4 pages load in addition to my home page, MSN, NoScrips,addblocker&welcome to Firefox 3.5. I want only my chosen home page to load
Name: Holly R. Blagg Email: hrblaggatyahoodotcom Product: Firefox Summary: 3.5 Beta- when I click on the home page button-4 pages load in addition to my home page, MSN, NoScrips,addblocker&welcome to Firefox 3.5. I want only my chosen home page to load Comments: From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this feedback but if you wish to provide one you must BCC (not CC) the sender for them to see it. ...

Click Event Needs To Change Click Event Handler
The following code successfully changes the ImageUrl and the ToolTip, but does not change the Click event handler. I've gotten as far as figuring out I can change the handler in the page load, which fires first, but that doesn't do me any good since what I change it to depends entirely on which click handler has fired. There are two imagebuttons on the page and each changes the two buttons to something else. What's the solution? public void Clans_Click(object sender, ImageClickEventArgs e) {     // This event was caused&nb...

Get logged on name prior to page load or page events.
Currently I am getting the logged in username from the Page_Load event and storing it in a session. Like so:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Session("IsUserValid") = User.Identity.Name End Sub This is causing a problem in some of my code. Also if the user is not directed to this page after login the session will never be created. Is there a way I can create a session to store the logged on username prior to the page load event and without using any page events? Thanks for any help! Hi,Try the Po...

Page load on every button click event
Can anybody help me out for restrict the page load on every control events. I am having login page and i want to redirect the authenticated page to new page. but each validation(Button click) the page is reload. How to get rid off it ?  Hi,Since HTTP is stateless you cannot do that as the page class gets re-instantiated everytime on Postback or page refresh. Refer this article for details:http://www.codeproject.com/KB/aspnet/lifecycle.aspxHope this helps,Vivek Social Networking Platform in ASP.NET || Join now: CodeASP.NET Community Please mark the most helpful reply/replies as &q...

Capturing a button click event in page load...
Hi, Does anyone know if its possible to capture a button click event within the page load area of an ASP page, using C#?   take a look at the __EventTarget value.  But why not catch it in the button click event?   Also look at the sender argument.  --JJPlease mark as answered if I helped. I don't answer personal emails unless I know you or of you. Feel free to post in the forum to get an answer from me. Request["__EVENTTARGET"] == Button.UniqueIDThanks, EdMicrosoft MVP - ASP/ASP.NET When i click a link button on my application, i execute the following...

event handling
hi all,  my first approach to asp.net as far as event handling was that i tended to put for example db logic to write or update in a button click event handler.  i came to find that things did not occur as expected when i did this...my alternate approach was to begin using the page_load event and for example call IsPostBack and inserting database logic there.  my question is this, are some type of hard and fast rules that go along with there being an appropriate place to handle say db specific events.  Or rather what is an example of logic i would want to put in the click...

Getting The Event's Name Fired In Page.Load Event Handler
Hi,How to get the event's name / type that is fired in Page.Load event handler? I'm trying to create an exceptional procedure in Page.Load event handler when some certain events are fired.Thanks in advance  i think you can try this code and modify it yor requirnment Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If IsPostBack = True ThenMe.Label1.Text = Me.Page.Request.Params.Get("__EVENTTARGET")  Dim ctrlname As String = Page.Request.Params.Get("__EVENTTARGET") If (Not ctrlname Is Nothing And ctrlnam...

click event not firing for linkbuttons created after page load (AJAX Enabled Page)
i have an Ajax page and initially a link button is created dynamically (Text for this button is First Button) and is attached to a div which acts as placeholder. Its click event is defined dynamically. After clicking the button it will create another one (Text for this one is Second Button) and its click event is defined at the time of creation. It is also attached to the previous div by clearing its contents. So far so good. After clicking this button (Second button), the click event is not firing. It is showing the previous state. i.e. First button is displayed Hierarchy should be like th...

Button click event to show progress bar or loading page
Really struggling with this problem.... My button click event fire a process which takes about 20 seconds to complete and then redirects to another page. The problem is that I want to show a message to let the user know the process is ongoing (as it is now the page just looks static for 20 seconds and then redirects). The process needs to be done on that page as it uses the page's datagrids and needs to be completed before it redirects. As the page doesn't render again I can't change a panel's visibility. Any ideas on what I can do.... I would hide a div tag on the same page. The ...

Web resources about - Button CLick Event + Page Load Event ( Why does Page load clear all my variables ) - asp.net.getting-started

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Staley: 'A lot of different variables...been a hard year'
... 41° Navigation Home Giants A's Sharks Warriors Kings 49ers Raiders Quakes Insiders More Tickets Shop Watch Staley: 'A lot of different variables...been ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

Resources last updated: 1/15/2016 6:56:25 AM