Reputation: 3
Fairly new to C# and while working through some tutorials I've hit a problem.
How would I pass the variable generated from one class back to the main form so that I can display it on a button click?
This code simulates a patient's heart rate:
class patientSim
{
int hr = new int();
public static genStats()
{
Random hr_ = new Random();
int hr = hr_.Next(40, 131);
}
}
This code should display the heart rate, hr, on button click.
public partial class mainForm : Form
{
public static void simBtn_Click(object sender, EventArgs e)
{
patientSim.genStats();
MessageBox.Show = hr;
}
}
I'm sure it's very simple but I can quite get my head around it.
Upvotes: 0
Views: 1108
Reputation: 25370
your method needs a return value:
public static int genStats()
{
Random hr_ = new Random();
int hr = hr_.Next(40, 131);
return hr;
}
then use that:
public static void simBtn_Click(object sender, EventArgs e)
{
int hr = patientSim.genStats();
MessageBox.Show(hr);
}
remember you have to declare a return value on your methods. If you don't want to return anything, you'd use void
Upvotes: 1
Reputation: 150108
The class patientsSim
(which by convention should be written PatientSim
has hr
defined as a private field. You need to modify that class in order to access it. One possible modification would be to add a getter to patientSim that returns the value of hr
:
public int Hr { get { return hr; } }
Then in your form
patientSim.genStats();
MessageBox.Show("HR: " + patientSim.Hr);
You have a few additional problems though:
int hr = hr_.Next(40, 131);
hides the class-level variable hr
. So change that to
hr = hr_.Next(40, 131);
Then, you have a mismatch between instance and statically scoped parts of your class. You can change the class level hr
to be static, along with the proposed getter, or change the event handler to be non-static.
Upvotes: 1