abcdefg
abcdefg

Reputation: 11

Passing Object and all of its values between forms

How do I pass an object and all of its values from Form A to form B?

Below is some 'hypothetical code' that I have produced where I search though a list in order to polymorphically book an Act. Once the name is found I then calculate the price based on hours booked. All of this is done using the object 's'. All of this code is on a button on Form A.

private void btnEnter_Click(object sender, EventArgs e)
{            
    string searchName = Convert.ToString(lstActs.SelectedItem);
    foreach (Singer s in singers)
    {
        if (String.Compare(searchName, s.Name) == 0)
        {
            s.HoursBooked = Convert.ToInt32(nudHours.Value);
            MessageBox.Show(Convert.ToString(s.HoursBooked), s.Name);
            double price = s.CalculatePrice(s.Price, s.HoursBooked);
            MessageBox.Show(Convert.ToString(price));
        }
    }


    Confirm myNewForm = new Confirm();
    myNewForm.ShowDialog();
    this.Hide();
}

Upvotes: 1

Views: 1789

Answers (2)

Marc
Marc

Reputation: 3959

Create a new class with the data you want to display:

public class ConfirmationData
{
    // some properties
}

Fill the object:

ConfirmationData data = new ConfirmationData();

string searchName = Convert.ToString(lstActs.SelectedItem);
foreach (Singer s in singers)
{
    if (String.Compare(searchName, s.Name) == 0)
    {
        s.HoursBooked = Convert.ToInt32(nudHours.Value);
        MessageBox.Show(Convert.ToString(s.HoursBooked), s.Name);
        double price = s.CalculatePrice(s.Price, s.HoursBooked);
        MessageBox.Show(Convert.ToString(price));

        .... fill 'data' with the Information you want to display
    }
}

Finally pass the data to the Confirm Dialog and show it:

Confirm myNewForm = new Confirm(data);
myNewForm.ShowDialog();

Upvotes: 3

Synthetic One
Synthetic One

Reputation: 405

Your Confirm class` work depends on the value of Singer class, doesnt it? If so, you can add a parameter to the Confirm constructor, like that:

public Confirm(Singer singer)
{
    //null-check I suppose
}

So the button press handler you wrote would end like this:

Confirm myNewForm = new Confirm(s);//where s is Singer
    myNewForm.ShowDialog();
    this.Hide();

Otherwise, you can add a new public property to Confirm class and assign a value to it before showing the dialog:

Confirm myNewForm = new Confirm();
myNewForm.Singer = s;
    myNewForm.ShowDialog();
    this.Hide();

Upvotes: 0

Related Questions