Thursday 29 December 2011

Access Master Page Control from Client Page

Hello everyone. here is a very simple but very useful trick to access Master Page Control from your child page in  code behind.
Some time we have to Change or Access the elements of master page from our client page.
Take a example of this real life work,that I faced today.
In my Master Page I have a label displaying the the total number of users selection. When ever a user adds a new item to his selection,the value must be updated. Here is a very simple code to achieve it

Button_Click(......)
{
      // CODE TO UPDATE YOUR DATABASE

        // get the label of Master Page
       Label lblCount=(Label)this.MasterPage.FindControl("lblDisplayCount");
       lblCount.Text= (int.Parse(lblCount.Text)+1).toString();


      //SAY IF YOU HAVE USER CONTROL IN MASTER PAGE
      Label lblCount=                                                           (Label)this.MasterPage.FindControl("UserControlId").FindControl("lblDisplayCount");
        lblCount.Text= (int.Parse(lblCount.Text)+1).toString();
}