Reputation: 11
I figured out how to read a text file using StreamReader
. Now I must create an array and Total all the values in index[1]
, the price.
My data reads as follows:
yellow cab, 62.12, 10/17/16
chick fil a, 9.50, 10/18/16
I currently only have 10 lines, however, there could be more added in the future.
I want to add 62.12 and 9.50 and enter the Total in txtBox_Total.text = Total.ToString();
Here is my current code:
private void btn_CalculateLoadExpenses_Click(object sender, EventArgs e)
{
string currentLine;
// Create StreamReader object to read Exams.txt
StreamReader examsReader = new StreamReader("TravelExpenses.txt");
listBox_Output.Items.Clear();
while (examsReader.EndOfStream == false)
{
currentLine = examsReader.ReadLine();
listBox_Output.Items.Add(currentLine);
}
}
Upvotes: 1
Views: 78
Reputation: 11
I must use StreamReader for this assignment. Here is more code I have written. Something is still incorrect as my total is not working. I am afraid I am making this more complicated than it needs to be.
private void btn_CalculateLoadExpenses_Click(object sender, EventArgs e) {
string[] purchase = new string[10];
float[] price = new float[10];
int index = 0;
string currentLine;
string[] fields;
float purchaseTotal, total = 0;
// Create StreamReader object to read Exams.txt
StreamReader examsReader = new StreamReader("TravelExpenses.txt");
listBox_Output.Items.Clear();
while (examsReader.EndOfStream == false)
{
currentLine = examsReader.ReadLine();
fields = currentLine.Split(',');
listBox_Output.Items.Add(currentLine);
purchase[index] = fields[0];
price[index] = total;
index++;
purchaseTotal = total;
txt_Box_Total.Text = total.ToString();
}
examsReader.Close();
}
Upvotes: 0
Reputation: 63065
you can read all lines at ones using File.ReadAllLines
string[] lines = File.ReadAllLines("TravelExpenses.txt");
then add all using Items.AddRange
listBox_Output.Items.AddRange(lines );
sum an be taken from the strings by splitting and taking sum of numbers like below
var Total= lines.Select(line =>line.Split(',')[1]).Select(num =>decimal.Parse(num)).Sum();
txtBox_Total.text = Total.ToString();
Upvotes: 1