Calling Parent Page Method From UserControl in C#

Introduction

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.

Objective of ParentPage Method

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.

Usercontrol 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.

private System.Delegate _delPageMethod;

public Delegate CallingPageMethod
{
    get { return _delPageMethod; }
    set { _delPageMethod = value; }
}

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.



protected void btnCall_Click(object sender, EventArgs e)
{
string Name = txtFN.Text +
+ txtLN.Text;
object[] obj = new object[1]; obj [0] = Name as object;
_delPageMethod. DynamicInvoke(obj);

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

delegate void DelUserControlMethod(string name);

protected void Page_Load(object sender, EventArgs e)
{
    DelUserControlMethod delUserControl = new DelUserControlMethod(DisplayName);
    uc.CallingPageMethod = delUserControl;
}

// Example method to be used with the delegate
private void DisplayName(string name)
{
    // Method logic here
}

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

public void DisplayName(string Name)
{
    lblHello.Text = "Hello" + Name;
}

Testing of the Code

Let's check the code with the following inputs

  • FirstName: Vipul
  • LastName: Malhotra

Output

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.


Similar Articles