Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to get a Value from a Child form back to Caller Form

0.00/5 (No votes)
5 Jul 2012 1  
how to get gridview selected row value to text box which is in another windows form

Introduction

This simple article explains how you can get a value on a different form on to a caller form.

Background

Basically you may keep a method to access the values in the child form window. Using a GET method is better than exposing the entire object to outside.

Using the code

Firstly You need to have a method in the child form to get the values. 

public DataGridViewSelectedRowCollection getselectedrow()
{
    return dataGridView1.SelectedRows;
}

Some example code to show how the child form is instantiated and the method being called.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Form2 form2show;
    private void button1_Click(object sender, EventArgs e)
    {
        if ((form2show==null) || (form2show.IsDisposed==true))
        {
            form2show = new Form2();
        }
        form2show.Show();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        if ((form2show==null) || (!form2show.Visible))
        {
            return;
        }
        DataGridViewSelectedRowCollection dsr = form2show.getselectedrow();
        if ((dsr == null) || (dsr.Count == 0))
        {
            return;
        }

        textBox1.Text = dsr[0].Cells[1].Value.ToString();
    }
}

Points of Interest

It's always better to use a method to access the properties like above. We call them GET methods. It's recommended than exposing entire object to outside.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here