Practical Approach of Creating and Reusing Custom Event Handler in ASP.NET C#


How to create a custom Event Handler class and predefine the methods to reuse it. This helps to reuse it.

  1. How to create a button dynamically at runtime
  2. How to add buttons to a form element.
  3. How to create a class for a custom event handler.
  4. How to create a method for an event handler.
  5. How to assign the custom event handler to a button.

Step 1: Used Namespaces:

using System;
using System.Web.UI.WebControls;

Step 2: Creating a Button at runtime and add to a Form element:

this.form1.Controls.Add(AddButton("Save", "save"));
this.form1.Controls.Add(AddButton("Delete", "delete"));

Step 3: Helps to create a Button at runtime and assign the event to it:

public
static Button AddButton(string text, string eventName)
{
   EventClass eventClass = new EventClass(); 
   Button but = new Button();
   but.Text = text;
   but.ID = text + "Button";
   but.Click += eventClass.AddEventHandler(eventName);
   return but;

}

Step 4: Creating a method for the event handler:

public void Save(object sender, EventArgs e)
{
   // Your code to save.
}


Step 5: Assigning a event method to the Event Handler:
but.Click += eventClass.AddEventHandler(eventName);

Step 6: Custom event class to predefine the events:

    public class EventClass
    {
        public EventHandler AddEventHandler(string eventName)
        {
            EventHandler handler = null
           
// if the event name is save it assing the Save method.
            if (eventName == "save")
            {
                handler = new EventHandler(Save);
            }
           
// if the event name is delete it assing the Delete method.
            else if (eventName == "delete")
            {
                handler = new EventHandler(Delete);
            } 
            return handler;
        } 
        public void Save(object sender, EventArgs e)
        {
           
// Your code to save.
        } 
        public void Delete(object sender, EventArgs e)
        {
           
// Your code to Delete.
        }
    }


Output:

eventhandler.png

Thanks for reading this article. Have a nice day.


Similar Articles