2012-11-26 86 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字符串屬性都被初始化爲空字符串。在寫入文件之前,您應該設置一些字符串。