带有方法的GUI

本文关键字:GUI 有方法 | 更新日期: 2023-09-27 18:09:25

我从我的控制台应用程序中获取了这段代码,我试图使它与GUI一起工作。是我调用的方法不对吗?我想点击OK按钮,在3个标签上分别显示数字的和、差、积。困惑。请帮助。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    namespace Numbers2GUI
    {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void okButton_Click(object sender, EventArgs e)
    {
        int num1 = 5;
        int num2 = 3;
        Sum(num1, num2);
        Difference(num1, num2);
        Product(num1, num2);
    }
    public static void Sum(int num1, int num2)
    {
        addLabel.Text = ("The sum of the numbers is {0}.", num1 + num2);
    }
    public static void Difference(int num1, int num2)
    {
        differenceLabel.Text = ("The difference of the numbers is {0}.", num1 - num2);
    }
    public static void Product(int num1, int num2)
    {
        double multiply = num1 * num2;
        productLabel.Text = ("The product of the numbers is {0}.", multiply);
    }
}

}

带有方法的GUI

我看到两个大问题:

  1. 使用string.Format方法格式化标签中的结果。
  2. 如果你想更新表单上的元素,你的Sum, DifferenceProduct方法应该而不是被声明为static

试试这个:

public void Sum(int num1, int num2)
{
    addLabel.Text = string.Format("The sum of the numbers is {0}.", num1 + num2);
}
public void Difference(int num1, int num2)
{
    differenceLabel.Text = string.Format("The difference of the numbers is {0}.", num1 - num2);
}
public void Product(int num1, int num2)
{
    double multiply = num1 * num2;
    productLabel.Text = string.Format("The product of the numbers is {0}.", multiply);
}