C Winform child forms access the controls and properties of the parent form

  • 2021-09-24 23:19:58
  • OfStack

Today, when I was designing an C # for contact management, I encountered this problem. I needed to pass the value in textBox in the parent form to the child form and perform database query operation. I used new parent form (). textBox. text; To carry out value transfer, but it is useless. After many experiments, a relatively simple solution has been found:

1. The child form calls the static variable of the parent form

Parent form: Logout

Subform: Affirm

Parent form text box: tB_Logout_Username


public partial class Logout : Form
{

  // Definition 1 Static variables hold the value of the text box in the parent form 

  public static string tB_LogoutName;

  // Instantiate the event of a child form 

  private void btt_Logout_Click(object sender, EventArgs e)
  {

    // Gets the value of the text box in the parent form 

    tB_LogoutName = tB_Logout_Username.Text;
    Affirm aff = new Affirm();
    aff.Show();

  }

}

Next, if you want to call it in the child form, you can directly: the parent form. Variable

Namely: Logout.tB_LogoutName

This method seems rather tricky, so it is reasonable to find the method to get the parent form first, and then operate on it.

2. Pass the parent form as a property to the child form

Define the parent form field of public in your child form, such as:


public class Affirm:Form
{
  public Logout MyLogout;
}

Then set its value in the parent form, such as:


public partial class Logout : Form
{
 
  // Definition 1 Static variables hold the value of the text box in the parent form 
 
  public static string tB_LogoutName;
 
  // Instantiate the event of a child form 
 
  private void btt_Logout_Click(object sender, EventArgs e)
  {
 
    // Gets the value of the text box in the parent form 
 
    //tB_LogoutName = tB_Logout_Username.Text;
    Affirm aff = new Affirm();
    aff.MyLogout=this;
    aff.Show();
 
  }
 
}

In this way, all the members exposed in the parent form can be accessed and used in the child form.


Related articles: