Click here to Skip to main content
15,888,090 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Angie_assignment
{
public partial class frmInventory : Form
{
//declare public variables and input user info into filestream
const string FILENAME = "INVENTORY.txt";
FileStream outFile = new FileStream(FILENAME, FileMode.Append, FileAccess.Write);

public frmInventory()
{
InitializeComponent();
}

private void btnAddSave_Click(object sender, EventArgs e)
{
//declare vairables
string description;
string price;
string code;
StreamWriter writer = new StreamWriter(outFile); // open text file

do
{
//input data
code = txtBoxCode.Text;
description = txtBoxDrscription.Text;
price = txtBoxCost.Text;

//write in info to text file
writer.WriteLine(code);
writer.WriteLine(description);
writer.WriteLine(price);

txtBoxCode.Text = "";
txtBoxDrscription.Text = "";
txtBoxCost.Text = "";
txtBoxCode.Focus();
}
while (rbtnLastEntry.Checked == false);


//close file
writer.Close();
outFile.Close();

}

}
}


I tried to do a loop and added a radio button that states whether the user is at their last entry to work around but still no use. Any help would be appreciated! :D
Posted

1 solution

Assuming the btnAddSave_Click is triggered by a click (as its name implies):
- you don't need while, just add to file.
- to ADD to file instead of having it OVERWRITTEN you need
C#
StreamWriter writer = new StreamWriter(outFile, True)
if you don't have second parameter, the file will be overwritten with the last values.

- consider using directive (
C#
using writer = new StreamWriter...{}

) for automatic closure and disposal. The code above has memory leak bug - if there is an exception in writing to file StreamWriter and File will not be closed.

Wrap entire thing into Try...Finally and close / dispose in finally block. Better solution is to simply use "using" keyword.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900