Friday, September 7, 2012

Access MasterPage variable in WebForm

     Today we will see how can we access a variable in our WebForm which was created in MasterPage.
     We will create a button in WebForm and when a user click on the button the value of that variable will be assigned to Button Text.

So let's Start

1. First Create a ASP.Net project, by clicking on File menu >> New >> Project

2. From the left menu Select Web and than from right menu select ASP.NET Web Application

3. Click on OK

Now we will add a Master Page, so

4. In Solution Explorer, right click on your project than Add >> New Item

5. Select Masterpage, and click on Add

6. In the code section of MasterPage create a public string name it "msg"

Public String msg="Put any Value";

7. Assign any value to this string you want

Now we will Add a WebForm in our project so

8. Right Click on your project >> Add >> New Item

9. Select WebForm using MasterPage

6. Click on Add, you will be ask to Select a Master Page, so select Site1.Master and click on OK

7. Now in Solution Explorer, right click on your WebForm and click on View Markup

Now here we have to define @MasterType directive
this is important to access any variable in MasterPage

8.  So just below Page Title, copy and paste the following line

         <%@MasterType VirtualPath="~/Site1.Master" %> 

9. Now make a button in your WebForm

10.  Double Click on the button to go into it's Coding

11. From here we can use the Master property and can use that string which we created in Master Page

    Now to change the button text, paste the following line inside Button Method


You can now easily access any variable of MasterPage in any of your WebForm.

If you have other WebForm and want to access variable Created in MasterPage than you will explicitly require to define MasterType directive in all your WebForm.

I hope this was informative for you, and I would like to Thank you for reading.

No comments:

Post a Comment