SoFunction
Updated on 2025-03-06

Summary of examples of communication method between child form and parent form in C#

This article summarizes the communication methods between C# child form and parent form. Share it for your reference. The details are as follows:

【The first method:】

first step:

Create an interface IForm, and the parent form inherits this interface

public interface IForm
{
    void RefreshForm();
}

Step 2:

The parent form implements the method in the interface, writes refresh code in the method to implement the interface

Form2 f = new Form2();
 = this;
();

Step 3:

Calling in the child form, refreshing method

Copy the codeThe code is as follows:
( as IForm).RefreshForm();

【The second method:】

1. Define refresh method in the parent form RefreshForm()
2. When the clicked event shows the child form, the code is as follows:

Form form=new Form();
(this);

3. In the click event of the child form, the code is as follows:

Copy the codeThe code is as follows:
( as Form).RefreshForm();

【The third method:】

Through event solutions:
Definition in the subform:

public delegate void sendmessage(string message); 
public event sendmessage SendTo ;

Main form:

ChildForm frm = new ChildForm(); 
 += new (SendArgs); 
(this);
private void SendArgs(string Message)//The main form receives messages{( "The main form has received the message: " + Message);}

Subform Test:

Copy the codeThe code is as follows:
if ( != null) ( "Have you received the main form?");

【The fourth method:】

By reference:

The following example shows how to implement your function through reference types:
Definition in the subform:

Copy the codeThe code is as follows:
protected MainForm ParentFrom = null;//Main Form

New constructor:

public ChildForm(MainForm parent) 
{ 
InitializeComponent();
 = parent;//Quote}

A Click in the main form:

ChildForm frm = new ChildForm(this); 
(this);

Subform Test:

void ...Click(....) 
{ 
 = "Test Quote"; 
if ( != null)  += "- " + ;//....... 
}

I hope this article will be helpful to everyone's C# programming.