【问题标题】:Return an updated list by clicking a button in C#通过单击 C# 中的按钮返回更新的列表
【发布时间】:2020-03-07 12:34:54
【问题描述】:

我有一个简单的表单,它有一个面板,其中包含一个带有四个 CheckButtons 作为答案的问题。 用户将浏览表格并为每个问题选择答案。 一旦他们单击按钮接受答案(代码下方的“buttonNewAnswer_Click”) 答案被合并到一个名为“answers”的列表中,然后我将其写入“results”并对其进行格式化,以便我可以将一行写入 .csv 文件。 涵盖所有问题后,用户将单击“buttonExit_Click”按钮 这会将“结果”写入 .csv 并退出应用程序。 不幸的是,我无法从“buttonNewAnswer_Click”到“buttonExit_Click”获得“结果”列表。 感谢您的帮助/建议。

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SIMPLE_FORM
{
    public partial class Form1 : Form
    {
        //public List<String> results = new List<String>();
    string myCsvFileTest = @"myFile.csv"


    // Button to update the answers list
        private void buttonNewAnswer_Click(object sender, EventArgs e)
        {

    // Algorithm to update the "answers" list

            var results = new StringBuilder();
            foreach (var i in answers)
            {
                results.AppendFormat("{0},", i.ToString());
            }
        }

    // Button to write the results to a .csv and then close the application
        private void buttonExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Press \"Yes\" to confirm closing the Application", " ", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (StreamWriter writer = new StreamWriter(myCsvFileTest, true, Encoding.UTF8))
                {
                    writer.WriteLine(results);  
                }
                System.Windows.Forms.Application.Exit();
            }
            else
            {
                this.Activate();
            }
        }   

我正在尝试从“buttonNewAnswer_Click”中获取“结果”列表,并在代码中的其他位置(例如“buttonExit_Click”)使用它来写入 .csv

【问题讨论】:

  • 将 StringBuilder 定义移到 click 事件之外,这样两个 click 方法都可以访问该变量。例如,myCsvFileTest 不在任何方法中。它在 Form 类的全局空间中。

标签: c# winforms button


【解决方案1】:

您需要将results 对象声明为Form1 类成员。

现在,您将其定义为 buttonNewAnswer_Click 函数中的局部变量 - 所以一旦函数结束,它就会被销毁。

基于问题中代码的简化代码:

public partial class Form1 : Form
{
    // declare and allocate
    StringBuilder results = new StringBuilder();

    private void buttonNewAnswer_Click(object sender, EventArgs e)
    {         
        // fill the results object
        foreach (var i in answers)
        {
            results.AppendFormat("{0},", i.ToString());
        }
    }

    private void buttonExit_Click(object sender, EventArgs e)
    {
        // you can use the result here.
        // results
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多