whomustnotbenamed whomustnotbenamed - 3 months ago 14
C# Question

Passing data from another form to another form

I have a problem regarding passing data from a form to another form.

This is for my assignment in school.

In my 1st form I have a button and 3 textboxes which are labeled id, name and address. When I click the button another form will appear and I also want the first form to be not accessible. The 2nd form shows list of data (id,names, addresses) which are from database which I have already created. After selecting the desired data there is a button labeled 'select' with the following code:

private void metroButtonSelect_Click(object sender, EventArgs e)
{
string selectedwcNo = metroGrid1.SelectedRows[0].Cells[0].Value.ToString();
string selectedwcFullname = metroGrid1.SelectedRows[0].Cells[1].Value.ToString();
string selectedwcAddress = metroGrid1.SelectedRows[0].Cells[2].Value.ToString();

}





and I dont know what to do next. I want to pass these data to my first form

Answer

Create a class for your values:

public class Person
{
    public string No {get; set;}
    public string Name {get; set;}
    public string Address {get; set;} 
}

In your second form add readonly public property, from where you get selected data.

public class SecondForm
{

    private Person _SelectedPerson;
    public Person SelectedPerson
    {
        get { return _SelectedPerson; }
    }

    //Set data to the SelectedPerson in your click eventhandler
    private void metroButtonSelect_Click(object sender, EventArgs e)
    {
        _SelectedPerson = new Person();
        _SelectedPerson.No = metroGrid1.SelectedRows[0].Cells[0].Value.ToString();
        _SelectedPerson.Name = metroGrid1.SelectedRows[0].Cells[1].Value.ToString();
        _SelectedPerson.Address = metroGrid1.SelectedRows[0].Cells[2].Value.ToString();
    }

}

Then in your first method create method which open Second form and return selected data

public class FirstForm
{

    private Person GetSelectedPerson();
    {
        Person selected = null;
        using(var secondForm = new SecondForm())
        {
            secondForm.ShowDialog();
            selected = secondForm.SelectedPerson;
        }
        return selected;
    }

    //And use above method in button click eventhandler
    private void Button_Click(object sender, EventArgs e)
    {
        Person selected = this.GetSelectedPerson();
        if(selected != null)
        {
            //use selected data for your purposes
        }
    }
}

secondForm.ShowDialog() method will show form as modal, which will make first form not accessible.