How can i write all my values in my datagrid not datagridview in a textfile i have the following code but it only saves the last values and not every value in the datagrid
my code
string file_name = "text.txt";
for (int i = 0; i < datagrid.Items.Count; i++)
{
//this is the class person
Person prsn = (Person)datagrid.Items[i];
File.WriteAllText(file_name, person.ToString());
}
How can i fix this?
File.WriteAllText
writes the data in your file but when the loop increments, that data is overwritten. This goes on till the last loop and that's why you see only the last one in the file.
You need to hold the previous data and should write in file only when the loop is complete.
So do this
string file_name = "text.txt";
StringBuilder strBuilder = new StringBuilder():
for (int i = 0; i < datagrid.Items.Count; i++)
{
Person prsn = (Person)datagrid.Items[i];
strBuilder.Append(prsn.ToString());
}
File.WriteAllText(file_name, strBuilder.ToString());