Search code examples
c#formsmdi

C# Passing of value from MDI parent form to child


I need help on how to pass value from MDI parent form to child form. In my parent form I have two radio buttons, MALE and FEMALE, I will choose one of these and by clicking the button will send the assigned value to the child form. Please see my code below:

Parent Form:

private void ButtonSelect_Click(object sender, EventArgs e)
        {
            if (this.rbMale.Checked)
            {
                string gender= "MALE";
                frmChild childform = new frmChild ();
                childform.GetGender = gender;

                frmChild  newMDIChild = new frmChild (); 
                newMDIChild.MdiParent = this; 
                newMDIChild.Show(); 

            }

            else if (this.rbFemale.Checked)
            {
                string gender= "FEMALE";
                frmChild childform = new frmChild ();
                childform.GetGender = gender;

                frmChild  newMDIChild = new frmChild (); 
                newMDIChild.MdiParent = this; 
                newMDIChild.Show(); 

            }
    }

Child Form:

public string GetGender { get; set; }

 private void frmChild_Load(object sender, EventArgs e)
        {
            if (GetGender  == Convert.ToString("MALE"))
            {
                 /*my code here*/
            }
            else if (GetGender  == Convert.ToString("FEMALE"))
            {
                /*my code here*/
            }
        MessageBox.Show(GetGender);
        }

I also temporarily put a MessageBox to let me know if it really fetch the value from the parent form, but it only returns empty.

I also tried this and this


Solution

  • You're creating two instances of your childForm, one for assigning the gender and other for showing it. You only need one instance, change your if else statement

    ...
    if (this.rbMale.Checked)
        {
           string gender= "MALE";    
           frmChild  newMDIChild = new frmChild (); 
           newMDIChild.GetGender = gender;
           newMDIChild.MdiParent = this; 
           newMDIChild.Show(); 
        }
    ...