1

这是我的文件(test.csv),由 datagridview 保存,下面的代码读取文件并将所有值粘贴到 datagridview 中。

InitializeComponent();
try
{
   //gbSeries.Enabled = false;
   //AssignValues();
   //btnSave.Enabled = true;

   // read and insert a new line
   System.IO.StreamReader csv_file = File.OpenText("c:/test.csv");

   while (csv_file.Peek() >= 0)
   {
      // read and add a line
      string line = csv_file.ReadLine();
      string[] vals = line.Split(';');

      dataGridView1.Rows.Add(new object[] 
      { 
         vals[0],
         vals[1],
         vals[2],
         vals[3],
         vals[4],
         vals[5],
         vals[6],
         vals[7]
         //cansim,
         //freeze });
      });
   }
   csv_file.Close();
}

我像这样保存我的datagrid视图数据:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
        string columnHeaderText = "";
        int countColumn = dataGridView1.ColumnCount - 1;

        if (countColumn >= 0)
        {
            columnHeaderText = dataGridView1.Columns[0].HeaderText;
        }

        for (int i = 1; i <= countColumn; i++)
        {
            columnHeaderText = columnHeaderText + ';' + dataGridView1.Columns[i].HeaderText;
        }

        csvFileWriter.WriteLine(columnHeaderText);
        foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
            dataGridView1.Rows = 1;
        {
            if (!dataRowObject.IsNewRow)
            {
                string dataFromGrid = "";
                dataFromGrid = dataRowObject.Cells[0].Value.ToString();

                for (int i = 1; i <= countColumn; i++)
                {
                    dataFromGrid = dataFromGrid + ';' + dataRowObject.Cells[i].Value.ToString();
                }
                csvFileWriter.WriteLine(dataFromGrid);
            }
        }
        csvFileWriter.Flush();
        csvFileWriter.Close();
    }
    catch (Exception exceptionObject)
    {
        MessageBox.Show(exceptionObject.ToString()); // If I don't have a value in the column then it throws exception. I don't want that. 
    }
}

包含列名称的第一行,我只想永远保存一次。问题是,每次我编辑我的datagridview并保存它时。包含列名称的第一行(如前所述)出现两次,如果我一次又一次地编辑,它每次都会使行名 + 1 变大。

first time:
Row names ---------
data --------------

After editing:

Row names ---------
Row names ---------
data --------------

After editing:

Row names ---------
Row names ---------
Row names ---------
data --------------

在我保存数据之前,我所有的 datagridview 列都需要有一个值。但我也想用空列保存数据,我能做些什么吗?当有一个空列时,它会引发异常,然后我的所有数据都消失了!

MessageBox.Show(exceptionObject.ToString()); // If I don't have a value in the column then it throws exception. I don't want that.

我应该如何保存第一行/行一次而不是每次。当我将文件读回datagridview时,我不想读取包含名称的第一行(已经存在)。

4

0 回答 0