'How to read and write array files in c# winforms
struct Grades
{
public string studentName;
public int midtermsGrades;
public int finalsGrades;
}
//create a 10 row array of Products:
Grades[] allGrades = new Grades[10];
int arrayIndex = 0;
private void Form1_Load(object sender, EventArgs e)
{
//read Products.txt file and place in array
for (int x = 0; x < 10; x++)
{
allGrades[x].studentName = "";
allGrades[x].midtermsGrades = 0;
allGrades[x].finalsGrades = 0;
}
StreamReader productReader = File.OpenText("Grades.txt");
string[] splitProduct = new string[3];
string oneProduct = "";
while (!productReader.EndOfStream)
{
oneProduct = productReader.ReadLine();
splitProduct = oneProduct.Split(',');
allGrades[arrayIndex].studentName = splitProduct[0];
StudentIDListBox.Items.Add(splitProduct[0]);
allGrades[arrayIndex].midtermsGrades = int.Parse(splitProduct[1]);
allGrades[arrayIndex].finalsGrades = int.Parse(splitProduct[2]);
arrayIndex++;
}
productReader.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
StreamWriter productWriter = File.CreateText("Grades.txt");
for (int x = 0; x < 10; x++)
{
//only write to file if product exists
if (allGrades[x].studentName != "")
{
productWriter.Write(allGrades[x].studentName + ",");
productWriter.Write(allGrades[x].midtermsGrades + ",");
productWriter.Write(allGrades[x].finalsGrades + ","); ;
}
}
//close
productWriter.Close();
}
I am trying to read in a txt file in my form load event so that a use can make a selection in the list box. When I load the form, the 10 rows show up in the list box, but after closing and reopening, only the first number is present. I need it to save any changes and reload with all 10 rows.
Solution 1:[1]
This is because you are writing out the text file incorrectly. At the beginning of each line is the name + numbers.
When you close, you write the data in one line. So you have to add a line break at the end:
//only write to file if product exists
if (allGrades[x].studentName != "")
{
productWriter.Write(allGrades[x].studentName + ",");
productWriter.Write(allGrades[x].midtermsGrades + ",");
productWriter.Write(allGrades[x].finalsGrades + ",");
productWriter.Write(Environment.NewLine);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Bartolomé |
