Tutorial :UserControl events in webform



Question:

I have an usercontrol which contains 3 buttons and 7 text boxes.I am calling that usercontrol dynamiclly in my webform using LoadControl.

But my problem here is

1.How to know which button(of user control) was clicked on my page?

2.How to raise those events?

Thanks Kavitha


Solution:1

Create event in your user control and fire it when button is clicked. So, you can manage this event from main page.

For more info please look at Easily Raise Events From ASP.NET ASCX User Controls


Solution:2

In your user control (WebUserControl1.ascx) you may have a Button1 with a click handler that acts like so:

Event Button1Click(ByVal button As Button)    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click    RaiseEvent Button1Click(sender)  End Sub  

And you can then dynamically attach an EventHandler to this in the parent control like so:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load      Dim buttonControl As WebUserControl1 = LoadControl("WebUserControl1.ascx")      AddHandler buttonControl.Button1Click, AddressOf ControlEventHandler  End Sub    Private Sub ControlEventHandler(ByVal ctl As Control)      'We now have access to this control's properties  End Sub  


Solution:3

You can handle the events of the controls on your usercontrol in its own codebehind file and raise events on your usercontrol that can in turn get handled by the codebehind file of your page.


Solution:4

The best thing is for the user control to encapsulate the controls inside of it, and for it to then raise a meaningful event. For instance, I wrote a date picker user control that has a RadioButtonList to select between "Last 12 months", "Year to date", or "Custom dates", and also start date and end date text boxes. My user control exposes a single DateChanged event, which it raises if a new radio button selection is made, or if the "Custom" selection is made and the input dates changed.

This way, the user of the control doesn't need to know about the complex implementation of the control. It just subscribes to the DateChanged event.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »