In this small article I am going to explain how to access a method of .aspx page into an UserControl.
In this small article iam going to explain how to process a method of our .aspx page into the user control and use it. For this intially add a web project. you will get Default.aspx page by default. Now right click the project solution and add a new item called WebUserControl.ascx.
Rename it as DemoWebUserControl.ascx
I will explain this using 3 steps :
1) First Design your Default.aspx page by adding the path of the user control in this way
2) Now add the respective User Control in this way in the same page
3) Now open Default.aspx.cs. Here we are going to add a simple method which returns a string that can be done in this way
return“DotNetFunda Is The Best Site For .Net Fundamentals !!!”;
4) Note that the class name for our file is _Default(This is default generated class name. For understanding purpose i am not changing it). This completes the work with Default.aspx page.
1) Now open DemoWebUserControl.ascx page and add a label in this way
2) Now after adding the label we have to call the method in Default.aspx for that open DemoWebUserControl.ascx.cs. Add this following code
overrideprotectedvoid OnLoad(EventArgs e)
// Casts the Page property to the desired type and access the method
lblTest.Text = ((_Default)this.Page).message();
3) Above mentioned code describes this would casts the Page property to the desired type so that we can access that method. The label text is assigned with the class name of parent page that is (_Default) and message is the mthod which we declared in the .aspx page
This step is very simple just run the code now !!!! You will able to access the method from .aspx page and display it in the user control in this way
By this way we can access the method of a .aspx page (content page) into a User Control.
Hope this helps !!!