Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Saving a DataGridView to file and loading

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 data into the control, hit the save button, and it save all the data to a file locally on the computer, and when I hit load, it loads the file and populates the control appropriately, keeping all rows, columns, and data the same as when saved.

Although it sounds fairly simple to me, I cant seem to figure a good way to save and load the data. Can I get a few pointers or examples to get myself started?

Thank you.

like image 731
Rekar Avatar asked Jun 01 '10 18:06

Rekar


2 Answers

Bind the DataGridView to a DataTable, and use the DataTable ReadXml() and WriteXml() methods to read and write the data to a file.

If you ever have multiple grids bound to multiple related tables, you can represent the schema with a DataSet and use the ReadXml() and WriteXml() methods of DataSet to read and write the whole schema.

There is an example on the MSDN page for DataTable.WriteXml() that you might find helpful.

like image 120
Igby Largeman Avatar answered Nov 12 '22 11:11

Igby Largeman


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<m;++i)
   {
         dgv.Rows.Add();
         for (int j = 0; j < n; ++j)
         {
               if (bw.ReadBoolean())
               {                                        
                     dgv.Rows[i].Cells[j].Value = bw.ReadString();                                        
               }
               else bw.ReadBoolean();
          }
     }
} 

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.

like image 29
Abolfazl Valadkhani Avatar answered Nov 12 '22 09:11

Abolfazl Valadkhani