-1

i am trying to write a code where the user enters delivery details into text box and the text gets added to a txt file (notepad txt file). This is my attempt, i get an extra line with " , ," why does it not add the text from textbox to the text file?

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);
        }
    }
} 
  • theDelivery is the object which is created from the class Delivery – littledevils326 Nov 26 '12 at 22:44
  • Code for writing to file looks fine, you even get `" , ,"`. So use the debugger and find out why `theDelivery.customerName` etc is empty. – weston Nov 26 '12 at 22:45
  • 2
    -1. Please align your title and sample code: your title asks about how to append to file, but your code and text of the question say that append works perfectly fine just with no values. – Alexei Levenkov Nov 26 '12 at 22:49

3 Answers3

2

The problem is that you're writing to the file on Form_Load. I assume that you only want to write to it when the user has changed something.

So you could handle a save-button's click-event to write to it:

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 is just another (comfortable) way to write to a file.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

..because you're not writing the contents of the textboxes to the file.. you're writing variables (that don't appear to be initialized anywhere):

Fixed:

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

Also, you're doing this on Form load.. is there data in the textboxes at this point (or is theDelivery initialized)?

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

Your customerName, customerAddress and arrivalTime string properties of the Delivery object insatance are all initialized to an empty string. You should set some string before you write to the file.

Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33