Riz
Riz

Reputation: 6982

ASP.Net - C# - Passing Page as parameter

I have a website. from each page of website I want to call a function which will receive a parameter of type Page. Each page will pass reference of itself to that function.

That function will hide and show some control on that page based on some logic.

Now I am not sure how to pass the page parameter. If I pass "this", I am unable to find any controls which I want to hide or show. This is my function

public static void Implement(string pageName, Page objPage)
    {
        if (pageName == "MANAGEMENT")
        {
            HyperLink obj = (HyperLink) objPage.FindControl("hlSave");
            if (obj != null)
            {
                obj.Visible = false;
            }
        }
    }

but objPage.FindControl("hlSave"); always returns null

Any idea whats wrong here?

Upvotes: 2

Views: 2727

Answers (1)

NaveenBhat
NaveenBhat

Reputation: 3318

If you are using master page then that might causing FindControl to return null. In that case you can use:

HyperLink obj = (HyperLink)objPage.Master.FindControl("ContentPlaceHolderID").FindControl("hlSave");

or you can recursively find hlSave using below method:

    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;
    }

you can use it like:

HyperLink obj = (HyperLink)FindControlRecursive(objPage, "hlSave");

Upvotes: 2

Related Questions