knowledgehunter
knowledgehunter

Reputation: 1415

passing variables into another form

I am developing a windows app in c#. I have used three decimal variables: counter, narrow, and broad which store different values based on some calculations.

On clicking a button, a message box is displayed showing these three decimal values and then the application exits..

Now I want to add another form having three labels in which these variable values needs to be shown. Please explain, how can I pass those variables in the next form to display in individual labels?

Upvotes: 1

Views: 3301

Answers (5)

Oll
Oll

Reputation: 945

Create a new Form...

public class CalculationResultForm : Form
{
    public CalculationResultForm(){}

    public decimal Counter
    {
        set { labelCounter.Text = value.ToString(); }
    }
    public decimal Broad
    {
        set { labelBroad.Text = value.ToString(); }
    }
    public decimal Narrow
    {
        set { labelNarrow.Text = value.ToString(); }
    }

    private void OkButton_Click(object sender, EventArgs e)
    {
        // This will close the form (same as clicking ok on the message box)
        DialogResult = DialogResult.OK;
    }
}

Then within your existing form button click handler...

private void MyButton_Click(object sender, EventArgs e)
{
    CalculationResultForm resultForm = new CalculationResultForm();
    resultForm.Counter = _counter;
    resultForm.Narrow = _narrow;
    resultForm.Broad = _broad;

    resultForm .ShowDialog();

    Application.Exit();
}

Upvotes: 1

overslacked
overslacked

Reputation: 4137

The easiest way is to probably add a new method, lets call it ShowWithDetails:

    public void ShowWithDetails(double Counter, double Narrow, double Broad)
    {
        CounterLabel.Text = Counter.ToString();
        NarrowLabel.Text = Narrow.ToString();
        BroadLabel.Text = Broad.ToString();

        ShowDialog();
    }

Upvotes: 1

Inisheer
Inisheer

Reputation: 20794

One method is to create a new constructor in the 2nd form. THen you can use those values from the 2nd form.

public Form2(decimal x, decimal y, decimal z):this()
{
   this.TextBox1.Text = Convert.ToString(x);
   this.Label1.Text = Convert.ToString(y);
   etc...
};

From main form

Form2 frm2 = new  Form2(x,y,z);
frm2.Show();

Upvotes: 3

Matthew Jones
Matthew Jones

Reputation: 26190

There is a blog post describing how to do this without using ShowDialog().

Upvotes: 0

tardomatic
tardomatic

Reputation: 2436

An easy way is to use properties. The form you want to pass the values to is just another class.

add something like this to the second form:

public int counter {get; set;}

then from the first form you'd do something along the lines of

Form2 form2 = new Form2();
form2.counter = 1;
form2.ShowDialog();

or something along those lines.

Upvotes: 0

Related Questions