Reputation: 311
I want to send a Value from a Textbox in a Form to a other class. I want to type in a number in the Textbox and pass this number back again. But I just get the number 0 as an Output. By clicking the Button its submits the Input and pass it over(in theory).
My code looks like this:
public int ReturnValue;
public void button1_Click(object sender, EventArgs e)
{
ReturnValue = int.Parse(textBox1.Text);
}
This is the codepiece from the other class, its in a case construct.
case "&Create Class Instance":
MultiplyInstance m = new MultiplyInstance();
m.Show();
int multiplier = m.ReturnValue;
The Value of the variable multiplier should be the Value I type in the textbox. But its always 0 when i print it. What am I doing wrong?
Upvotes: 0
Views: 90
Reputation: 430
Replace m.Show() with m.ShowDialog().
case "&Create Class Instance":
MultiplyInstance m = new MultiplyInstance();
m.ShowDialog();
int multiplier = m.ReturnValue;
Show() an a form will open the form and immediatly execute the next line in your code int multiplier = m.returnValue which is stiil 0 at this point.
Also change the Button Click event to
private void button1_Click(object sender, EventArgs e)
{
ReturnValue = int.Parse(textBox1.Text);
Close();
}
as you have to close the form to return to your class.
You should also make button1_click private as it can only be executed by the form.
Upvotes: 1
Reputation: 43300
Use ShowDialog
instead of Show()
, What you are getting is the default value of an integer as your forms process has continued while you have the form showing.
case "&Create Class Instance":
using(MultiplyInstance m = new MultiplyInstance())
{
m.ShowDialog();
int multiplier = m.ReturnValue;
}
ShowDialog
makes the form modal so it will block execution whilst your form is open (this also means you can't access your other form while this form is open)
Upvotes: 2