【问题标题】:saving text box data to .txt file and displaying the data on another form text boxes将文本框数据保存到 .txt 文件并在另一个表单文本框中显示数据
【发布时间】:2012-04-21 15:00:53
【问题描述】:

我正在创建一个简单的应用程序来从文本框中捕获客户数据并将其保存在驱动器 C 中的文本文件中,字符串由逗号分隔。并在第二个表单上显示存储的数据,该表单通过按钮从第一个表单激活我到目前为止编写的代码如下,有人可以帮我解决我哪里出错了。

代码编译没有错误,但显示警告: variable FILE in form2 is declared but not used..。当我在没有调试的情况下开始时,它会崩溃并报告错误:

类型初始化器 'InvoiceDataAppGaoria.Form2' 抛出异常(Form2 F2=new Form2())

当我将数组元素分配给文本框时,IDE(visual studio 2008) 会报告错误。

Form2

namespace InvoiceDataAppGaoria
{
    public partial class Form2 : Form
    {
        static string FILE = @"C:\Csharp\coursework1\maucha.txt";
        static FileStream outFile = new FileStream("FILE", FileMode.Open, FileAccess.Read);
        static StreamReader read = new StreamReader("FILE");
        static string line = read.ReadLine();
        static string[] values = line.Split(',');
        string invoicetxt = values[0];
        string lname = values[1];
        string fname = values[2];
        string AMT = values[3];

        public Form2()
        {
            InitializeComponent();
        }

    }
}

Form1

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

namespace InvoiceDataAppGaoria
{
   public partial class Form1 : Form
    {
      const string DELIM = ",";
      const string FILENAME = @"C:\Csharp\coursework1\maucha.txt";
      int invoNum;
      string lname,fname;
      double AMT;
      static FileStream outFile = new    FileStream("FILENAME",FileMode.Create,FileAccess.Write);
      StreamWriter writer = new StreamWriter(outFile);
      public Form1()
      {
        InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
        invoNum = Convert.ToInt32(invoicetxt.Text);
        lname = lnameBox.Text;
        fname = fnameBox.Text;
        AMT = Convert.ToDouble(amtBox.Text);
        writer.WriteLine(invoNum+DELIM+lname+DELIM+fname+DELIM+AMT);
      }
      private void button2_Click(object sender, EventArgs e)
      {
        Form2 F2 = new Form2();
        F2.Show();
      }

   }

}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    当您创建文件流时,您使用字符串 "FILE" 而不是变量 FILE。它应该看起来像这样:

    static string FILE = @"C:\Csharp\coursework1\maucha.txt";
    static FileStream outFile = new FileStream(FILE, FileMode.Open, FileAccess.Read);
    static StreamReader read = new StreamReader(FILE);
    

    顺便提一下:你真的应该把你的变量命名为file,而不是FILE。坚持通用的命名约定会让阅读其他人的代码更加愉快。

    【讨论】:

    • 哈哈,当我第一次在手机上看到这篇文章时,我以为你会写“你需要使用"FILE" 而不是FILE”:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2020-03-29
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多