简体   繁体   中英

How to pass dynamic variables to another form?

I have two Forms Form1 and Form2, both of them are already "connected" with eachother. I am already passing button signals, trackbar values, timer ticks..., between them.

The connections looks like this inside Form1:

private void Form1_Load(object sender, EventArgs e)
    {
        Form2 = new Form2(timer1,btnBoost,btnBrake);
        Form2.Show();
    }

and inside Form2:

public Form2(Timer timer,Button Boost,Button Brake)
    {
        InitializeComponent();
        _timer = timer;
        _boost = Boost;
        _brake = Brake;          
    }

Now I would like to pass a variable from Form1 which is changing it's value every timertick to Form2, to create a graph.

Inside Form1 it looks like this

public partial class Form1 : Form {

public double ValueThatIWant;

}

Way done im giving it a value

private void Timer1_Tick1(object sender, EventArgs e){

ValueThatIWant = Math.Sqrt(somevalue.X,somevalue.Y);
}

I've already tried to access the variable by calling Form1 from Form2

Form1.valueThatIWant

but since

public double valueThatIWant

is declared public, it's value is always 0.

private void FillChart()
    {

       this.chart1.Series["Velocity"].Points.AddXY(time,Form1.ValueThatIWant);

    }

//That's the method I've created in Form2 to create a chart.

I would like to call the variable from inside(?) the

public Form1()

method, so that i get the changing value, and not only 0.

Hope that kinda describes my problem.

Thanks in advance!

You need access to the instance where you change the values. In your code Form2 does not know anything about that instance except btnBoost and btnBreak . You need to provide a reference to your Form1 -instance to your constructor of Form2 :

public Form2(Timer timer, Form1 f1, Button Boost, Button Brake)
{
    InitializeComponent();
    _form1 = f1;
    _timer = timer;
    _boost = Boost;
    _brake = Brake;          
}

In your Form1 -code you now need this:

private void Form1_Load(object sender, EventArgs e)
{
    Form2 = new Form2(timer1,this,btnBoost,btnBrake);
    Form2.Show();
}

instead of:

private void Form1_Load(object sender, EventArgs e)
{
    Form2 = new Form2(timer1,btnBoost,btnBrake);
    Form2.Show();
}

Now you can access _form1.ValueIWant within Form2 .

Furthermore you could also omit the two buttons from the constructor, as they probably are components of Form1 anyway. In this case you need to make the appropriate fields within Form1 public properties, however:

class Form1
{
    public Button BreakButton => btnBreak;
}

in which way you can now use _form1.BreakButton .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM