C# - Saving a DataGridView to file and loading

前端 未结 2 942
鱼传尺愫
鱼传尺愫 2021-01-02 18:44

To start off, what I have is a simple Winforms app, with just a save and load button, and with a datagridview control to hold data. What I am looking to do is input some dat

2条回答
  •  心在旅途
    2021-01-02 19:32

    I have tested a simple way to save datagridview to a file :

    //DataGridView dgv=...
    string file= "c:\\mygrid.bin";
    using (BinaryWriter bw = new BinaryWriter(File.Open(file, FileMode.Create)))
    {
        bw.Write(dgv.Columns.Count);
        bw.Write(dgv.Rows.Count);
        foreach (DataGridViewRow dgvR in dgv.Rows)
        {
           for (int j = 0; j < dgv.Columns.Count; ++j)
           {
               object val=dgvR.Cells[j].Value;
               if (val == null)
               {
                    bw.Write(false);
                    bw.Write(false);
                }
                else
                {
                    bw.Write(true);
                    bw.Write(val.ToString());
                 }
             }
        }
    

    and for loading such a file into a datagridview:

    //DataGridView dgv = ...
    dgv.Rows.Clear();
    string file="c:\\mygrid.bin";
    using (BinaryReader bw = new BinaryReader(File.Open(file, FileMode.Open)))
    {
       int n=bw.ReadInt32();
       int m=bw.ReadInt32();
       for(int i=0;i

    Consider that I have assumed that the datagridview control has fixed columns, in you specific situation you should add some codes to insert new columns or create a new gridview.

提交回复
热议问题