我无法在文件中打印结果

时间:2011-10-08 23:49:42

标签: c#

它在这一行中遇到了一个错误:foreach(textBoxes中的var textBox)。它无法识别 :textBoxes.i尝试写为TextBox并再次打我一个错误。我有Visual C#2010 Express版

public Form1()
{
    InitializeComponent();

    private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};

    private List<string> storeItems = new List<string>();
}

private void button1_Click(object sender, EventArgs e)
{
    var buffer = new StringBuilder();
    foreach(var textBox in textBoxes)
    {
        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.BackColor = Color.FromName("LightSalmon");
            MessageBox.Show("This item cannot be left blank");
            textBox.Focus();
            return;
        }
        textBox.BackColor = Colors.FromName("Window");
        buffer.Append(textBox.Text);
    }

    var result = buffer.ToString();
    storeItems.Add(result);
    System.IO.File.AppendAllText(@"C:\Users\v\Desktop\text.txt", Environment.NewLine + result);
}

3 个答案:

答案 0 :(得分:2)

看起来你正试图在构造函数中创建字段。你做不到,做这样的事情:

private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};

private List<string> storeItems = new List<string>();

public Form1()
{
    InitializeComponent();
}

看起来你的大写错了。 TextBoxes与C#中的textBoxes不同。

答案 1 :(得分:1)

此行放在错误的位置。

private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};

您的变量TextBox仅在构造函数中被识别。你必须把它放在类中,而不是放在类的方法中。

例如在此行之后:

public partial class Form1 : Form

或者甚至喜欢这样:

public Form1()
{
    InitializeComponent();

    private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};

    private List<string> storeItems = new List<string>();
}
private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};
private void button1_Click(object sender, EventArgs e)
{

编辑:正如Svick所说,这条线也不在正确的位置:

private List<string> storeItems = new List<string>();

遵循相同的规则。

答案 2 :(得分:-1)

当您尝试通过TextBoxes进行预告时,您的数组textBoxes是否大写?

相关问题