c# - 通过单击 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
解决方案
您需要将该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
}
}
推荐阅读
- notepad++ - 将文本数字替换为记事本++中的文件名
- python - python中“is”关键字的行为?
- python - 虚拟环境中的 django-serializers 错误
- git - 如何在提交前恢复并进入上一个阶段
- reactjs - KeyboardAvoidingView 没有调整高度
- django-rest-framework - 使用自定义用户模型 (DRF) 显示作者链接
- java - 每次调用 doReturn 时如何返回一个新实例?
- python - Plotly:如何通过字符串列表和坐标列表注释图形?
- linux - Amazon Linux 2 / Red Hat Linux Enterprise:binutils 不会安装“ld”bin
- azure - 更改 Kusto 中使用 make-series 操作生成的日期时间格式