我正在创建一个简单的应用程序来从文本框中捕获客户数据并保存在驱动器C中的文本文件中,字符串由逗号分隔。并在第二个表单上显示存储的数据,该表单是通过按钮从第一个表单激活的。我到目前为止编写的代码如下所示,有人可以在我出错的地方帮助我。
代码编译没有错误,但它显示警告:
variable FILE in form2 is declared but not used..
。当我在没有调试的情况下启动时,它会因错误报告而崩溃:
的类型初始值设定项 'InvoiceDataAppGaoria.Form2'抛出异常(Form2 F2 = new Form2())
当我将数组元素分配给文本框时,IDE(visual studio 2008)会报告错误。
窗体2
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();
}
}
}
答案 0 :(得分:2)
创建文件流时,使用字符串 "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
。坚持常见的命名约定使得阅读其他代码变得更加愉快。