What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this:
MyPage.aspx:
I found the same solution on OdeToCode that @lordscarlet linked to in his accepted solution. The problem was that I needed a solution in VB rather than C#. It didn't translate perfectly. Specifically, checking if the event handler is null in OnBubbleClick didn't work in VB because the compiler thought I was trying to call the event, and was giving an error that said "... cannot be called directly. Use a 'RaiseEvent' statement to raise an event." So here's a VB translation for the OdeToCode solution, using a control called CountryDropDownList.
For starters, let’s create a user control with a dropdown attached.
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="CountryDropDownList.ascx.vb" Inherits="CountryDropDownList" %>
United States
Afghanistan
Albania
The code behind for the user control looks like the following.
Public Class CountryDropDownList
Inherits System.Web.UI.UserControl
Public Event SelectedCountryChanged As EventHandler
Protected Sub ddlCountryList_SelectedIndexChanged(sender As Object, e As EventArgs)
' bubble the event up to the parent
RaiseEvent SelectedCountryChanged(Me, e)
End Sub
End Class
An ASPX page can now put the user control to work.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="UpdateProfile.aspx.vb" Inherits="UpdateProfile" MaintainScrollPositionOnPostback="true" %>
<%@ Register Src="~/UserControls/CountryDropDownList.ascx" TagPrefix="SO" TagName="ucCountryDropDownList" %>
WebForm1
In the code behind for the page:
Protected Sub OnSelectedCountryChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedCountryChanged
' add your code here
End Sub