Reputation: 43
I am new to c# and I just need something basic. I am trying to call a method from a button click and I don't know if I declare an object and method in Program.cs or Form1.cs
Here is what I have so far.
public partial class frmMain : Form
{
Form form = new Form();
public frmMain()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
txtC.Text = form.CalcHypotenuse(double.Parse(txtA.Text), double.Parse(txtB.Text));
}
}
public string CalcHypotenuse(double sideA, double sideB)
{
double hypotenuse = Math.Sqrt((sideA * sideA) + (sideB * sideB));
string hypotenuseString = hypotenuse.ToString();
return hypotenuseString;
}
Upvotes: 0
Views: 3620
Reputation: 27009
Methods need to be inside a class. Your form is a class so just put the method inside it and then you can call it. Please note I have moved the method inside the frmMain
class and removed the line Form form = new Form();
since you do not need it.
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
// the 'this' is optional so you can remove it
txtC.Text = this.CalcHypotenuse(double.Parse(txtA.Text), double.Parse(txtB.Text));
}
public string CalcHypotenuse(double sideA, double sideB)
{
double hypotenuse = Math.Sqrt((sideA * sideA) + (sideB * sideB));
string hypotenuseString = hypotenuse.ToString();
return hypotenuseString;
}
}
If you are only calling the method from within your form only, then make it private too so it can not be called from outside.
Upvotes: 1