A Question about Events

  • Thread starter Thread starter DC
  • Start date Start date
D

DC

In a book sample I am working through in ASP.NET, a simple Hello World works
fine, but the order of events has me confused.

The sample involves a Button control and the onClick event. On click, the
page reloads and voila, hello world is written (I understand this part).

However, when I set a breakpoint on both Page_Load and onClick, Page_Load is
accessed first, stepping through takes me to onClick.

But "Hello World" is written outside of all HTML elements. I was under the
impression that on Page_Load the HTTP stream is persisted until processing
of events is completed, so why isnt Hello World written in the HTML elements
(specifically, the BODY tag)?

Thank you!
 
The HTML tags are processed after the load. I am not sure which book you are
working with, but it is a bad ASP.NET example (many are). As ASP.NET works
on a binding model, you are best to place a container (a panel comes to
mind) on the page and add controls (for plain text, use a LiteralControl).

Page_Load runs every time the page loads. So, it is natural it will run
every time. It is not a great event to slap in a bunch of stuff; use the
button event instead. The normal signature should be something like:

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
//Something that runs on a hit without a postback
}
else
{
//Code that runs EVERY time a page is posted back to
//NOTE: Do not make a conditional tree here,
// use the postback events instead
}
}

In most books, you see the horrible code tree like:

if(!Page.IsPostback)
//set up initial page
else
if condition1
// lots of code here
else if condition 2
//lots of code here
else
//lots of code here

protected void btnWhatever_Click(object sender, EventArgs e)
{
//empty routine
}

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
 
Back
Top