Today, when I was designing a contact management C#, I encountered this problem. I needed to pass the value in the textBox in the parent form to the child form and perform database query operations. I used new parent form().; to pass the value, but it was useless. After many experiments, I found a relatively simple solution:
1. The child form calls the parent form's static variable
Parent form: Logout
Subform: Affirm
Parent form text box: tB_Logout_Username
public partial class Logout : Form { //Define a static variable to store the value of the text box in the parent form public static string tB_LogoutName; // Events that instantiate subform private void btt_Logout_Click(object sender, EventArgs e) { //Get the value of the text box in the parent form tB_LogoutName = tB_Logout_Username.Text; Affirm aff = new Affirm(); (); } }
Next, you need to call it in the child form directly: parent form. variable
That is: Logout.tB_LogoutName
This method seems to be more flawless. In theory, you should first find a way to get the parent form and then operate 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 { //Define a static variable to store the value of the text box in the parent form public static string tB_LogoutName; // Events that instantiate subform private void btt_Logout_Click(object sender, EventArgs e) { //Get the value of the text box in the parent form //tB_LogoutName = tB_Logout_Username.Text; Affirm aff = new Affirm(); =this; (); } }
In this way, you can access and use all the members exposed in the parent form in the child form.