将数据加载到gridview

时间:2013-05-28 09:18:26

标签: c# datagridview

我有一个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时,它每次都会添加一个额外的列(没有标题)。

有人能告诉我这段代码有什么问题吗?

2 个答案:

答案 0 :(得分:3)

当你保存时,你用逗号结尾。因此,当文件被回读时,它认为末尾有一个额外的(空)值。尝试:

rowValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

答案 1 :(得分:0)

在将数据网格值保存到CSV的同时,检查网格计数视图列(它的数量是多少??实际上有多少列。?)在button1_Click中。

仔细调试您的代码。

您是否在button1_Click中尝试了类似的内容:

     `cols = dataGridView1.Columns.Count - 1;`

    for (int i = 0; i < cols - 1; i++)
    {
        wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
    }