c#datagridview 修改数据保存到文件中
时间: 2023-10-02 07:08:23 浏览: 230
要将 C# DataGridView 中修改的数据保存到文件中,您可以按照以下步骤进行操作:
创建一个 DataTable 对象,将 DataGridView 中的数据复制到该对象中。
使用 StreamWriter 将数据写入文件中。
下面是一个示例代码:
// 创建 DataTable 对象
DataTable dt = new DataTable();
// 将 DataGridView 中的数据复制到 DataTable 中
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.Name);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dr = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dr[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dr);
}
// 将数据写入文件中
StreamWriter sw = new StreamWriter("data.txt");
foreach (DataRow row in dt.Rows)
{
foreach (object item in row.ItemArray)
{
sw.Write(item.ToString() + ",");
}
sw.WriteLine();
}
sw.Close();
在这个示例中,我们首先创建了一个 DataTable 对象,并将 DataGridView 中的数据复制到该对象中。然后,我们使用 StreamWriter 将数据写入名为 "data.txt" 的文件中。在写入数据时,我们先遍历 DataTable 中的每一行,然后遍历每个单元格的值,并将它们以逗号分隔的形式写入文件中。
注意:这个示例只是一个简单的实现方式,您可以根据自己的需求进行修改和优化。
相关推荐















