Calling a method in parent page from user control

前端 未结 10 1170
暖寄归人
暖寄归人 2020-11-28 23:01

I\'ve a user control registered in an aspx page On click event of a button in the user control, how do i call a method which is there in the parent page\'s code

10条回答
  •  独厮守ぢ
    2020-11-28 23:17

    I love Stephen M. Redd's answer and had to convert it to VB. Sharing it here. Suggested edits welcome.

    In the user control's code-behind:

    Public Class MyUserControl
        Inherits System.Web.UI.UserControl
    
        'expose the event publicly
        Public Event UserControlButtonClicked As EventHandler 
    
        'a method to raise the publicly exposed event
        Private Sub OnUserControlButtonClick()
    
            RaiseEvent UserControlButtonClicked(Me, EventArgs.Empty)
    
        End Sub
    
        Protected Sub lbtnApplyChanges_Click(sender As Object, e As EventArgs) Handles lbtnApplyChanges.Click
    
            'add code to run here, then extend this code by firing off this event
            'so it will trigger the public event handler from the parent page, 
            'and the parent page can hanlde it
    
            OnUserControlButtonClick()
    
        End Sub
    
    End Class
    

    In the parent page subscribe to the event, so when the event is raised, your code will run here.

    Public Class SalesRecord
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            'hook up event handler for exposed user control event to handle this
            AddHandler MyUserControl.UserControlButtonClicked, AddressOf MyUserControl_UserControlButtonClicked
    
        End Sub
    
        ''' 
        ''' code to run when user clicks 'lbtnApplyChanges' on the user control
        ''' 
    
        Private Sub MyUserControl_UserControlButtonClicked()
    
            'this code will now fire when lbtnApplyChanges_Click executes
    
        End Sub
    
    End Class
    

提交回复
热议问题