【问题标题】:Keeping score across multiple Form windows在多个表单窗口中记分
【发布时间】:2016-04-05 15:09:49
【问题描述】:

我正在做一份包含 10 个问题的问卷。 First Form.cs 只是开始按钮,在新的 Form.cs 中打开第一个问题。

新表单有 3 个单选按钮,每个按钮应返回不同的点(0、5、10)。这些点应在所有表单中累积,然后应在最终的 Form.cs 中显示总数或上传到 SQL 等。

我尝试过编写代码,但不确定这是最好的方式。

namespace XX
{
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    int points;
    int totalscore = 0;

    private void btnCANCEL_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
    }

    private void zeropoint_CheckedChanged(object sender, EventArgs e)
    {
        if (zeropoint.Checked == true)
        {
            points = 0;
            totalscore = totalscore + points;
        }

    }

    private void fivepoint_CheckedChanged(object sender, EventArgs e)
    {
        if (fivepoint.Checked == true)
        {
            points = 5;
            totalscore = totalscore + points;
        }
    }

    private void tenpoint_CheckedChanged(object sender, EventArgs e)
    {
        if (tenpoint.Checked == true)
        {
            points = 10;
            totalscore = totalscore + points;
        }
    }

    Form3 thirdForm = new Form3();
    private void btnOK_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        this.Hide();
        var form3 = new Form3();
        form3.FormClosed += (s, args) => this.Close();
        form3.Show();

    }

}

【问题讨论】:

  • 你的帖子不清楚问题是什么或你在问什么。
  • 您可以将分数传递给每个表单的构造函数
  • 如果您尝试在表单之间共享不断变化的信息,您可能需要查看 C# 委托。

标签: c# windows forms


【解决方案1】:

我会创建一个类,将您的分数保存为一个字段。您将在主窗体中存储对该类对象的引用。打开新表单时,您可以将对象引用传递给该表单。在关闭单独的表单后,仍然可以通过主表单中的引用访问该对象中分数的所有更改。

此外,如果您发现需要额外的共享数据,您可以简单地将字段添加到分数类,以便在任何地方都可以访问它们。

【讨论】:

    【解决方案2】:

    听起来您想要一个静态成员来跟踪您在班级所有实例中的总分。看看这个。

    https://msdn.microsoft.com/en-us/library/79b3xss3.aspx#Anchor_0

    并将您的总数更改为

    public static int totalcount = 0;
    

    【讨论】:

      【解决方案3】:

      你想要一个静态类

      static class Scoring
      {
          public static int CurrentPoints { get; set; }
          public static int TotalScore { get; set; }
      
      }
      

      然后调用它

      Scoring.CurrentPoints += 10;
      

      【讨论】:

        猜你喜欢
        • 2020-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        • 2012-06-24
        • 1970-01-01
        相关资源
        最近更新 更多