Sunday, November 6, 2016

C# ASP.NET Web Forms: Create Custom Event in Web User Control and Subscribe to It

Hello guys,

I tried this to add a custom event to a UserControl and Subscribed to it from the main page containing the UserControl, it is very easy little steps, but very helpful, you will find below screen shots, and an attached solution file as a sample

  1. In the user control before the class declare an event as follows "public event EventHandler eventname;"
  2. Raise the event in whatever event you want as follows "if(eventname != null) this.eventname(object, e);"




(001. Solution Files) 

(002. User Control UI)

User Interface for the UserControl - a simple drop down that when changed it raise the drpChanged event in the user control
(003. User Control Code)



  1.  in the MainPage,  drag the user control
  2.  open the main page in the design mode - source, and go to the user control and add the attribute "OnEventName=name_of_the_event_handler"
(004. Main Page UI)




 (005. Main Page HTML)


(006. Main Page UI after firing the event)




 You can find the complete c# sample code under Our Slack Channer 
https://itggeeks.slack.com/files/tarek/F2T1J69M4/usercontroleventexample.rar



No comments:

Post a Comment