Click here to Skip to main content
15,917,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My form has one textBox1 filled with value 100 and dataGridView1 has two columns filled as shown down here. After clicking button1and saving them to the text file, then clearing dataGridView1, filling again with the second records as shown after first records starting with textBox1 value of 200,
Then append to end of text file, my problem how can I write to text file number of records 3 in first case and 4 in second one, on the top position directly on the right hand side of textBox1 value:

(First Records)
100
5 100
10 105
15 99
(Second Records)
200
25 120
34 123
45 146
60 122
Output text file should be like this:

100 3
5 100
10 105
15 99
200 4
25 120
34 123
45 146
60 122

What I have tried:

Private void button1_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(filenane, true);
sw.WriteLine(" "+textBox1.Text);
for(int row=0;row<dataGridView1.RowCount; row++)
{ 
    dataGridView1.Rows[row].HeaderCell.Value = (row + 1).Tostring();
String value =    dataGridView1[0,row].Value as string;
      if (value != null)
      {
         textLine= " \t" + textLinr + " " + 
dataGridView1[col,row].Value.Tostring();
      }
}
Sw.WriteLine(textLine);
}
Posted
Updated 8-Jun-19 20:05pm

1 solution

That's complicated - and I'll ignore your code since it won't even compile, let alone do anything useful.
Why is it complicated? Because text files don't have "lines" - they can contain "end of line" characters line '\n' but that is just interpreted as a line end character when you read the file. Which means if you try to write a number at the beginning of the file, then you have to plan ahead, because if the new number has more or less digits than the existing one, you have to rewrite the entire file to keep it working!

You code is muddled - you are appending data to you file, yes - but you have a loop which overwrites the value you are going to write so only the last value will be added, but you loop through all the rows to get there! I'd strongly suggest you sit down and think about what you are trying to do before you go any further.

What I'd do (apart from use a "real" database instead which is probably some weeks away in your course) is copy from the old file to a new file, writing your new "header" information first, then delete the old file, and rename the new. Also ave a look at the File class: File Class (System.IO) | Microsoft Docs[^] with particular reference to the ReadAllLines and WriteAllLines methods - they will make your code a lot "cleaner".
 
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