views:

73

answers:

3

i have user control called shopping cart. which i have used in master page. i want to get the textbox value from the child page in to user control. is it possible to access control from child page in "Custom User Control" which is on master page?

A: 

I'm not entirely sure what your trying to accomplish but it sounds like to want to access a property of a user control contained in a master page from a content page.

You can use a public property in your master page which exposes the text property of the user control.

public string ShoppingCartText {
    get { return ((TextBox)this.ShoppingCart.FindControl("TextBox1")).Text; }
    set { ((TextBox)this.ShoppingCart.FindControl("TextBox1")).Text = value; }
}

Then from your content page you can set the value of the text box. You can access the properties of a master page from a content page through the Page.Master property.

Master.ShoppingCartText = "value"
Phaedrus
A: 

What I did was access the master page control through a public function in the code behind.

So in the code behind for the master page, I would declare something like:

public string getTextBoxValue() { return TextBox.Text; }

Jimmy W
Pragnesh Patel
A: 

You can recurse through the control tree to find any control in a page.

Here are a couple of extension methods, pop this code in a class file in your solution.

public static class ControlExtensions
{
        public static IEnumerable<Control> FindAllControls(this Control control)
        {
            yield return control;

            foreach (Control child in control.Controls)
                foreach (Control all in child.FindAllControls())     
                    yield return all;
        }

        public static Control FindControlRecursive(this Control control, string id)
        {
            var controls = from c in control.FindAllControls()
                           where c.ID == id
                           select c;

            if (controls.Count() == 1)
                return controls.First();

            return null;
        }
    }

Then use like this in your user control.

TextBox whatYoureLookingFor = this.FindControlRecursive("theId") as TextBox;

if(null != whatYoureLookingFor)
    // whatever
Greg B