+ 2
I creat a datagridview and i want to save data in file txt how i do that ?
5 Antworten
+ 2
Do you use winform or wpf ?
To understand what you want to do.
The user enters the data into a datagrid and you want to save that data in to a file
+ 3
There are 2 tasks in this question
1) get the data from the datagrid
private void button1_Click(object sender, EventArgs e)
{
string Data = ""; //place holder voor the data in a row
foreach (DataGridViewRow row in dataGridView1.Rows) //loop through every row in the grid
{
Data = ""; //reset data for every next row
if (!row.IsNewRow) //check if the row is a new row or a row that already contains data
{
for (int i = 0; i < dataGridView1.Columns.Count; i++) //loop through every column
{
String cellText = row.Cells[i].Value.ToString(); //that data from individual cell
Data += cellText + " "; //add this data to the Data variable
}
WriteLineToFile(Data, @"C:\Temp\Temp.txt"); //write the line in the textfile
}
else
{
//this is a new row, this does not contain any data yet so it gives a null reference exception
}
}
}
2) write data to file
private void WriteLineToFile(string Line, string path)
{
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine(Line);
}
}
This is the quickest way to do it.
It is not good practice.
You are not separating UI from data.
You do not use objects or datasources
It does work though
+ 2
Yes
+ 2
Winform or wpf
+ 1
Windows form