Search code examples
asp.netvb.netuser-controlsascxfindcontrol

How to access control from parent aspx from its child ascx


I try to access the MainContentBlock control from the aspx, but unable to do so.

In the aspx file I have registered both controls:

<uc3:ContentBlock ID="MainContentBlock" runat="server" DynamicParameter="id" DefaultContentID="3951" /></uc3>

<uc3:childshow ID="Childshow" runat="server"/></uc3>

In the code behind for child.ascx

If Me.Parent.Page.FindControl("MainContentBlock") IsNot Nothing AndAlso Me.MainContentBlock.Item.Id = 4357 Then

...

But the error says BC30456: 'MainContentBlock' is not a member of 'child'.

It's almost like the ".parent" part did not work.

However, If I try the following:

If Me.Parent.MainContentBlock IsNot Nothing AndAlso Me.MainContentBlock.Item.Id = 4357 Then

...

It will bring up the error "BC30456: 'MainContentBlock' is not a member of 'System.Web.UI.Control'.

and seems it at least recognized the .parent part again.

confused... please help, thanks.


Solution

  • It's because you're trying to reference MainContentBlock as a property of the child control. When you use Me.MainContentBlock, Me refers to the child control.

    You just need to use FindControl, and properly reference the found control:

    Dim myBlock As ContentBlock = TryCast(Me.Parent.FindControl("MainContentBlock"), ContentBlock)
    
    If myBlock IsNot Nothing Then
        'do things with myBlock
    End If