2012-11-26 84 views
-1

我想写一个代码,其中用户输入交货详细信息到文本框中并将文本添加到txt文件(记事本txt文件)。 这是我的尝试,我得到一个额外的行“,,”为什么它不会将文本从文本框添加到文本文件?将文本附加到文本文件的问题?

private void FrmDelivery_Load(object sender, EventArgs e) 
{ 
    if (theDelivery != null) 
    { 
     txtCustomerName.Text = theDelivery.customerName; 
     txtCustomerAddress.Text = theDelivery.customerAddress; 
     txtArrivalTime.Text = theDelivery.arrivalTime;  
     using (StreamWriter writer = new StreamWriter("visits.txt", true)) //true shows that text would be appended to file 
     { 
      writer.WriteLine(theDelivery.customerName + ", " + theDelivery.customerAddress + ", " + theDelivery.arrivalTime); 
     } 
    } 
} 
+0

theDelivery是从类创建的对象交付 – littledevils326

+0

写入文件的代码看起来很好,你甚至会得到'',',''。所以使用调试器并找出为什么'theDelivery.customerName'等是空的。 – weston

+2

-1。请对齐你的标题和示例代码:你的标题询问如何附加到文件,但你的代码和问题的文本说,追加工作完美罚款,没有价值。 –

回答

1

..because你不写的文本框的内容文件..你写变量(没有出现在任何地方初始化):

修正:

writer.WriteLine(txtCustomerName.Text + ", " + txtCustomerAddress.Text + ", " + txtArrivalTime.Text); // Fixed. 

另外,你正在这样做表格加载..是否有数据在这一点上的文本框(或是theDelivery初始化)?

+0

我有两种形式,主窗体中有一个列表框,显示交货情况,当您单击其中一个交货单时,其详细信息以另一种形式显示。 – littledevils326

+0

您的方法不起作用 – littledevils326

+1

然后,您的代码中存在更大的问题。在该行放置一个断点..是否有文本框或变量中的任何数据? –

2

问题是您正在写入文件。我假设你只想在用户改变某些内容时写信给它。

所以,你可以处理一个保存按钮的点击事件来写它:

private void FrmDelivery_Load(object sender, EventArgs e) 
{ 
    if (theDelivery != null) 
    { 
     txtCustomerName.Text = theDelivery.customerName; 
     txtCustomerAddress.Text = theDelivery.customerAddress; 
     txtArrivalTime.Text = theDelivery.arrivalTime;  
    } 
} 

private void btnSave_Click(object sender, System.EventArgs e) 
{ 
    string line = string.Format("{0},{1},{2}{3}" 
       , txtCustomerName.Text 
       , txtArrivalTime.Text 
       , theDelivery.arrivalTime 
       , Environment.NewLine); 
    File.AppendAllText("visits.txt", line); 
} 

File.AppendAllText只是另一个(舒适)的方式写入文件。

0

Delivery对象insatance的customerName,customerAddress和arrivalTime字符串属性都被初始化为空字符串。在写入文件之前,您应该设置一些字符串。