简体   繁体   中英

c# how do I use a method in a Windows Forms App?

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;
}

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.

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