eastboundr
eastboundr

Reputation: 1877

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.

Upvotes: 0

Views: 8323

Answers (3)

Maciej
Maciej

Reputation: 7961

FindControl works but the pain is that what you're looking for can be higher then just at parent level. Here is a handy method I use:

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    foreach (Control ctl in root.Controls)
    {
        Control foundCtl = FindControlRecursive(ctl, id);

        if (foundCtl != null)
            return foundCtl;

    }
    return null;
}

Upvotes: 0

KP.
KP.

Reputation: 13730

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

Upvotes: 1

James Johnson
James Johnson

Reputation: 46047

Depending on where the control is located on the page, you may need to find it recursively, but in a simple situation you would just do this:

var pnl = Page.FindControl("MainContentBlock") as Panel; //or whatever it is
if (pnl != null)
{
    //your code here
}

Here's a recursive method if you need it:

public Control FindControlRecursive(string controlID, Control parentCtrl)
{
    foreach (Control ctrl in parentCtrl.Controls)
    {
        if (ctrl.ID == controlID)
            return ctrl;
        FindControlRecursive(controlID, ctrl);
    }
    return null;
} 

And you would call it like this:

var pnl ((PageName)Page).FindControlRecursive("MainContentBlock") as Panel;

Upvotes: 0

Related Questions