简体   繁体   中英

How do I read parent control's id in user control's page load, independent of pages?

I have a common User Control, say, TextBoxUserControl.ascx, which is used in three different pages, say, A.aspx, B.aspx and C.aspx.

A.aspx has a hidden control, say, hiddenA
B.aspx has a hidden control, say, hiddenB
C.aspx has a hidden control, say, hiddenCxyz

I want to read parent page's hidden value from the TextBoxUserControl.ascx when TextBoxUserControl.ascx is loaded from different pages.
But, the problem I am facing is how not to explicitly code hidden fields name in Page_Load of TextBoxUserControl.ascx ? How to decouple between them ?

Below is Page_Load method of TextBoxUserControl.ascx

Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    ' below hiddenA of A.aspx is explicitly being checked, but it wont work if this user control
    ' is used in B.aspx and C.aspx as they have different names of hidden fields
    Control ctr = Me.Parent.FindControl(hiddenA)
    labelTotal = ctr.Text
End Sub

The way that I would implement this is to create an interface for the hosting pages that returns the appropriate value (don't even worry about the control).

For example:

Public Interface IPageHost
   ReadOnly Property PageNameGuid As String
End Interface

Then, implement this interface in a.aspx:

Public Class APage
    Inherits System.Web.UI.Page
    Implements IPageGuidHost

    Public ReadOnly Property PageNameGuid As String Implements IPageGuidHost.PageNameGuid
        Get
            Return hiddenA.Text
        End Get
    End Property

and finally, in the user control, if the parent page implements the interface, just get the value directly:

Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim parentPage As IPageGuidHost

    parentPage = TryCast(Me.Page, IPageGuidHost)
    If parentPage IsNot Nothing Then
        labelTotal.Text = parentPage.PageNameGuid
    Else
        lableTotal.Text = String.Empty
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM