我有一个DataGridView
,我想将其内容保存到 CSV 文件。然后当我再次运行程序时,它将数据从 CSV 文件加载到 gridview。
我有这个代码保存到 CSV 文件:
private void button1_Click(object sender, EventArgs e)
{
FileInfo todel = new FileInfo(@"c:\dd\GB STOCK.csv");
todel.Delete();
int cols;
//open file
StreamWriter wr = new StreamWriter(@"c:\dd\GB STOCK.csv");
//determine the number of columns and write columns to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols ; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
//close file
wr.Close();
}
这段代码从csv加载到gridview:
private void Form1_Load(object sender, EventArgs e)
{
string rowValue;
string[] cellValue;
if (System.IO.File.Exists(@"C:\dd\GB STOCK.csv"))
{
System.IO.StreamReader streamReader = new StreamReader(@"C:\dd\GB STOCK.csv");
// Reading header
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i <= cellValue.Count() - 1; i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i];
column.HeaderText = cellValue[i];
dataGridView1.Columns.Add(column);
}
// Reading content
while (streamReader.Peek() != -1)
{
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
dataGridView1.Rows.Add(cellValue);
}
streamReader.Close();
}
else
{
MessageBox.Show("No File is Selected");
}
}
现在的问题是,每当我保存并加载 gridview 时,它每次都会添加一个额外的列(没有标题)。
谁能告诉我这段代码有什么问题?