w0051977
w0051977

Reputation: 15817

Handling Page lifecycle events

I am a VB.NET Developer trying to learn C# in my spare time. Please see the code below:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;//event handler code
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string test = "got here";
        }

    }

This is a Windows Form app. If I add the event handler code to the constructor then Form1_Load handles the load event.

Now see the Web Forms app below:

public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string s = "got here";
        }
    }

Page_Load is fired without any event handler code?

My question is: Are Page Life Cycle events automatically wired to function names e.g. Page_Load automatically handles the page load in c# ASP.NET? Why does this not apply to Windows Forms? Where do you put the Event Handler code in windows forms? the .designer?

Upvotes: 0

Views: 411

Answers (2)

Winform do not auto fire event as Asp.Net because winform has not page life Cycle. To handle a event in winform, you select a component in design mode. Look at the right panel, you will see the events tab. There are alot event here. Double click to handle it. enter image description here

Upvotes: 0

Daniel Manta
Daniel Manta

Reputation: 6718

In Asp.Net you can set AutoEventWireup value. Please check this article https://support.microsoft.com/en-us/kb/324151

However when I need to handle an event the easiest way for me is going to the aspx source view, find the the runatserver control and specify my handler there. For example:

<asp:TextBox ID="txtCustomer" runat="server" />

As you type "on..." the list of events is shown (events are identified by ray icon), select OnLoad and Create.

<asp:TextBox ID="txtCustomer" OnLoad="txtCustomer_Load" runat="server" />

Now go to your cs code behind file and you'll see default handler was created there.

protected void txtCustomer_Load(object sender, EventArgs e)
{

}

Another option is going to Design View, right click on the control and go to properties. Click on the ray icon and add your handler.

Upvotes: 1

Related Questions