Here's a brief example, suitable for beginners, of the differences between windows forms and ASP.NET. In short, the windows forms has real state while running, while ASP.NET has a convincing illusion of it on pages.
We have a simple page, a form containing a label:
<head runat="server">
<title>Demo page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
The code behind the form creates a button at runtime:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button button1 = new Button();
button1.ID = "Button1";
button1.Text = "Click me";
button1.Click += new EventHandler(Button1_Click);
Form.Controls.Add(button1);
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "The button was clicked at " + DateTime.Now.ToString();
}
}
The page shows with a button on it, and when the button is clicked, a postback occurs, then the page on the server executes the button click handler, and the text on the label reads:
The button was clicked at 02/04/2007 22:21:40
Here's a modified version:
protected void Page_Load(object sender, EventArgs e)
{
Button button1 = new Button();
Random rands = new Random();
button1.ID = "Button" + rands.Next(10000).ToString();
button1.Text = "Click me";
button1.Click += new EventHandler(Button1_Click);
Form.Controls.Add(button1);
}
This is the same except the button has a randomised name. Clicking the button on this form has no effect, unless you get extremely lucky with random numbers and get the same value twice in a row.
There are lots of ways to avoid making this kind of mistake, but it underscores the point: The page that gets the postback is not the same page that serviced the original request, it is a new instance. In this case, it has a different button on it. And if the control data coming back to it is not found on the page, that control's event request will be discarded.
If you know what you're dealing with, you can make it work for you.