Search code examples
asp.net.netupdatepanelparent-child

Setting parent page controls visibility from Child user control page


I have a parent page Page1 which has button1. Page1 has a usercontrol uc1. uc1 has an update panel inside which a grid grid1 is present. I am trying to set Page1.button1's visibility to false, depending on the row command event(there are some if conditions in the row command event) of uc1.grid1. I am setting Page1.button1's visibility in the following way:

Create a IsButton1Visible property in uc1. Set the property in UC1.Grid1.RowCommand to false, on page1 PreRender event, access IsButton1Visible and set Page1.button1 visibility.

Even though in quick watch Page1.button1 visibility is set to false at the line of assignment, when I see the UI, it is still visible. I don't know what I am doing wrong. Or the way that I am getting hold of button1 and its visibility is not correct.

In general can we set a Parent page's control's property from a user control during the user control event?


Solution

  • If you use the event-driven model approach

    Delegate/EventArgs code:

    public class ButtonVisiblityEventArgs : EventArgs
    {
        public ButtonVisiblityEventArgs(bool visible)
        {
            this.Visiblity = visible;
        }
    
        public bool Visiblity { get; private set; }
    }
    
    public delegate void UpdateParentButtonVisibilityEventHandler(object sender, ButtonVisiblityEventArgs args);
    

    User control code:

        public event UpdateParentButtonVisibilityEventHandler RaiseUpdateParentButtonVisibilityEvent;
    
        private void RequestParentButtonVisibilityChange(bool setVisible)
        {
            if (RaiseUpdateParentButtonVisibilityEvent != null)
            {
                RaiseUpdateParentButtonVisibilityEvent(this, new ButtonVisiblityEventArgs(setVisible));
            }
        }
    

    And in your command handler, just call:

        RequestParentButtonVisibilityChange(false);
    

    whenever you want to hide the button. On your page:

        protected void Page_Load(object sender, EventArgs e)
        {
            this.RaiseUpdateParentButtonVisibilityEvent += new UpdateParentButtonVisibilityEventHandler(uc_RaiseUpdatecurrentDisplayPanelRequestEvent);
        }
    
        private void uc_RaiseUpdatecurrentDisplayPanelRequestEvent(object sender, ButtonVisiblityEventArgs args)
        {
            button1.Visible = args.Visiblity;
        }