As already pointed out in solution 1, simply move the relevant portions of the code to another method and call that.
Few other observations based on the snippet you posted
- You correctly use TryParse to convert the values from text boxes. However, you don't investigate if the parsing fails. TryParse returns a boolean so you should check if it is true or false and act based on that
- It looks like you have a class level variable (
potentialEnergy
) that you use to transfer data from the method (
Calculate
). If that is correct, it's considered as a bad habit. Instead, define the Calculate method so that it returns the answer as a return value
Pseudo example
==============
public void btnCalculate_Click(object sender, EventArgs e) {
DoCalculation();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
txtHeight.Text=trackBar1.Value;
DoCalculation();
}
public void DoCalculation() {
double mass;
double height;
double gravity;
bool ok = true;
ok &= double.TryParse(txtMass.Text, out mass);
ok &= double.TryParse(txtHeight.Text, out height);
ok &= double.TryParse(txtGravity.Text, out gravity);
if (!ok) {
return;
}
txtAns.Text = Calculate(mass, height, gravity);
}
public double Calculate(double mass, double height, double gravity) {
return result;
}