Calling Parent Page Method From UserControl in C#

I encountered this requirement when I needed to call a method of the page from the UserControl (with a parameter) and based on that need to make some changes to the controls on the main page.

I have used delegates for this purpose and it's because of this that I encountered a good use of delegates as well.

Scenario

We have a User Control with two textboxes and a button. The textboxes are to get the First and the Last Name and on clicking the button, the values will then pass to the main page and would be displayed as a Hello Message on the label of the main page.

Screen

The screen is as in the following with which the control belongs to the main page that belongs to the User Control.

User Control

Usercontrol Code

Now, we declare a property on the User Control.cs file as in the following code snippet:

Usercontrol Code

The property is of the type Delegate because that's how we want to use it further.

On the click of the button, we will pass an argument to this delegate as in the following:

argument to this Delegate

Page Code

Now, on the page, we declare a delegate with a parameter and assign a function to it as in the following:

delegate

Now, in the definition of the method, we will display the name in the label on the main page:

display

Testing:

Let's check the code with the following inputs:

  • FirstName: Vipul
  • LastName: Malhotra

The output is:

output
The current situation might be a small one, but this can easily be used in a more complex situation as well.

Also, please find the code attached for a better understanding.

Up Next
    Ebook Download
    View all
    Learn
    View all