Search code examples
c#visual-studiowinformstextbox

Show the value in textbox in the parent form, of a cell selected of the gridview in the child form


This is my code: IN Parent form:

public void tokenform_Load(object sender, EventArgs e)
    {
       tbvarchecker.Text = HelpForm.code;
    }
   private void TextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        HelpForm help = new HelpForm();
        if (e.KeyCode == Keys.F2)
        {               
            help.Show();               
        }
    }
    public void setvalues(string cd)
    {
        tbvarchecker.Text = cd;
        label10.Text = cd;
    }

  Child Form code:
     private void dgv(object sender, DataGridViewCellMouseEventArgs e)
    {
        DataGridViewRow row = dgvshowallfields.Rows[e.RowIndex];

        code = row.Cells[0].Value.ToString();
        code1 = row.Cells[0].Value.ToString();
        this.Close();
    }

    private void HelpForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        tokenform tkf = new tokenform();
       tkf.setvalues(code);
        tkf.setvalues(code1);
        tkf.tokenform_Load(sender,e);

    }

    //private void HelpForm_FormClosing(object sender, FormClosingEventArgs e)
    //{
    //    tkf.setvalues(code);
    //}

This code is declared as public static string code, while the code1 is just string. I have also checked through breakpoints and the value reaches the function in Parent form function set values but still, I couldn't show it in the textbox. Guys can anyone help me out.....??


Solution

  • First, pass the parent form to your Show() call.

    Change:

    help.Show();
    

    To:

    help.Show(this);
    

    Then, in the child form, you can cast the .Owner property to your parent form type and call its methods:

    private void HelpForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        tokenform tkf = this.Owner as tokenform;
        if (tkf != null) 
        {
            tkf.setvalues(code);
            tkf.setvalues(code1);
            tkf.tokenform_Load(sender,e);
        }
    }