Creating the Form

To demonstrate how to use server side events, we will create a simple web form with some buttons on it. Then, we will add code to the server side event handlers of these buttons to demonstrate how they work. To begin, create a new ASP.NET Empty Web Site and:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a label onto the web form.
  8. Add a break line.
  9. Drag and drop a button onto the web form.
  10. Add a break line.
  11. Drag and drop a button onto the web form.
  12. Add a break line.
  13. Drag and drop a button onto the web form.
  14. Add a break line.
  15. Drag and drop a button onto the web form.
  16. Add a break line.
  17. Drag and drop a button onto the web form.
  18. Add a break line.
  19. Drag and drop a button onto the web form.

We should now have a form with a label and 6 buttons on it. First, we need to add the event handlers for each of these buttons. To begin, open Default.aspx up to design mode and:

  1. Double click Button1.
  2. Change the name of the generated event method from ‘Button1_Click’ to ‘Buttonx_Click’.
  3. Set the OnClick property of Button2 to ‘Buttonx_Click’.
  4. Set the OnClick property of Button3 to ‘Buttonx_Click’.
  5. Double click Button4.
  6. Double click Button5.

Now we have all of the events for our buttons. Notice that buttons 1 through 3 are all bound to the same event handler method. To demonstrate how to use the same event handler for multiple buttons, we will show how you can determine what button is being clicked based on the event arguments. To do this, add the following code to the Buttonx_Click event method:

Next, add the following code to the Button4_Click event method:

Then, add the following code to the Button5_Click event method:

This code will display the button that has been clicked in our label in the event that the user clicks it. Next, add the following code to the Page_Load event method:

This will call the events for button 4 and 5 when button 6 is clicked.

Testing

To test this out, load up the web site and click all of the buttons. Ensure that the correct text appears in the label. This demonstrates how easy you can use server side events on your controls.

Download Source Files