首页 > 解决方案 > 通过单击 C# 中的按钮返回更新的列表

问题描述

我有一个简单的表单,其中包含一个包含四个 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

标签: c#winformsbutton

解决方案


您需要将该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
    }   
}

推荐阅读