none
3 datagridviews in einer Datei speichern RRS feed

  • Frage

  • Guten Tag zusammen,

    ich habe eine Anwendung, in der ich einen Tab-Control mit 3 Tabs und daher auch 3 DataGridViews habe. Da ich nicht jedes DGV einzeln in einer Datei speichern möchte, bevor ich das Programm schließe, möchte ich wissen, ob und wie es funktioniert, diese 3 DGV's in einer Datei zu speichern, und dann wieder zu laden, sodass alle Daten wieder in ihrem DGV sind.

    Da ich noch Anfänger bin, würde ich mich über Code freuen...

    Vielen Dank schon mal

    Sonntag, 28. April 2019 15:14

Antworten

  • Kann ich...

    Hab mal ein "Minimal-Beispiel" gebastelt.

    Eine Form mit 3 DatagridView und der Code:

    Form:

    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsAppDataGridJsonSample
    {
        public partial class Form1 : Form
        {
            private const string FileName = @"C:\Temp\testDaten.json";
    
            private Data DataCollection;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                if (File.Exists(FileName))
                {
                    DataCollection = Json.ReadFromJsonFile<Data>(FileName);
                }
                else
                {
                    DataCollection = new Data();
                }
                dataGridView1.DataSource = DataCollection.DataTab1;
                dataGridView2.DataSource = DataCollection.DataTab2;
                dataGridView3.DataSource = DataCollection.DataTab3;
    
            }
    
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                Json.WriteToJsonFile<Data>(FileName, DataCollection);
            }
    
        }
    
        public class Data
        {
            public Data()
            {
                DataTab1 = new BindingList<DataTab1>();
                DataTab2 = new BindingList<DataTab2>();
                DataTab3 = new BindingList<DataTab3>();
            }
            public BindingList<DataTab1> DataTab1;
            public BindingList<DataTab2> DataTab2;
            public BindingList<DataTab3> DataTab3;
        }
    }

    DataModel:

    namespace WindowsFormsAppDataGridJsonSample
    {
        public class DataTab1
        {
            public DataTab1()
            {
                
            }
            public override string ToString() => $"{Column1};{Column2};{Column3}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
        }
    
        public class DataTab2
        {
            public DataTab2()
            {
    
            }
            public override string ToString() => $"{Column1};{Column2};{Column3};{Column4}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public string Column4 { get; set; }
        }
    
        public class DataTab3
        {
            public DataTab3()
            {
    
            }
            public override string ToString() => $"{Column1};{Column2};{Column3};{Column4};{Column5}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public string Column4 { get; set; }
            public string Column5 { get; set; }
        }
    }

    Json Serialisierung/Deserialisierung:

    using System.IO;
    
    namespace WindowsFormsAppDataGridJsonSample
    {
        public static class Json
        {
            /// <summary>
            /// Writes the given object instance to a Json file.
            /// <para>Object type must have a parameterless constructor.</para>
            /// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
            /// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
            /// </summary>
            /// <typeparam name="T">The type of object being written to the file.</typeparam>
            /// <param name="filePath">The file path to write the object instance to.</param>
            /// <param name="objectToWrite">The object instance to write to the file.</param>
            /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
            public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
            {
                TextWriter writer = null;
                try
                {
                    var contentsToWriteToFile = Newtonsoft.Json.JsonConvert.SerializeObject(objectToWrite);
                    writer = new StreamWriter(filePath, append);
                    writer.Write(contentsToWriteToFile);
                }
                finally
                {
                    try
                    {
                        if (writer != null)
                            writer.Close();
                    }
                    catch { }
                }
            }
    
            /// <summary>
            /// Reads an object instance from an Json file.
            /// <para>Object type must have a parameterless constructor.</para>
            /// </summary>
            /// <typeparam name="T">The type of object to read from the file.</typeparam>
            /// <param name="filePath">The file path to read the object instance from.</param>
            /// <returns>Returns a new instance of the object read from the Json file.</returns>
            public static T ReadFromJsonFile<T>(string filePath) where T : new()
            {
                TextReader reader = null;
                try
                {
                    reader = new StreamReader(filePath);
                    var fileContents = reader.ReadToEnd();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(fileContents);
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }
            }
        }
    }

    Und hier das kleine Projekt zum Download: https://1drv.ms/u/s!AlsOa7F9kTVPrtBuclruRDDhyTLkpQ

    Gruß


    Freiberufler im Bereich Softwareentwicklung Von der PLC und Robotik zu VB.NET & C#, vorrangig WPF und UWP


    Montag, 29. April 2019 08:01
  • Hi Stefan,
    hier mal eine kleine vollständige Demo von mir. Einfach den Code in eine leere Form kopieren:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
    
        private DataGridView dgv1 = new DataGridView() { Dock = DockStyle.Top };
        private DataGridView dgv2 = new DataGridView() { Dock = DockStyle.Top };
        private DataGridView dgv3 = new DataGridView() { Dock = DockStyle.Top };
        private Button btnLoad = new Button() { Text = "Load data", Dock = DockStyle.Top };
        private Button btnSave = new Button() { Text = "Save data", Dock = DockStyle.Top };
        private string fileName = @"c:\temp\DemoData.json";
        private Data Daten;
        private BindingSource bs1 = new BindingSource();
        private BindingSource bs2 = new BindingSource();
        private BindingSource bs3 = new BindingSource();
    
        private void Form03_Load(object sender, EventArgs e)
        {
          this.Controls.AddRange(new Control[] { dgv3, dgv2, dgv1, btnSave, btnLoad });
          this.btnLoad.Click += BtnLoad_Click;
          this.btnSave.Click += BtnSave_Click;
        }
    
        private void BtnLoad_Click(object sender, EventArgs e)
        {
          if (File.Exists(this.fileName))
          {
            using (StreamReader rdr = new StreamReader(fileName))
            Daten = JsonConvert.DeserializeObject<Data>(rdr.ReadToEnd());
          }
          else
          {
            this.Daten = new Data();
          }
          this.bs1.DataSource = Daten.List1;
          this.dgv1.DataSource = bs1;
          this.bs2.DataSource = Daten.List2;
          this.dgv2.DataSource = bs2;
          this.bs3.DataSource = Daten.List3;
          this.dgv3.DataSource = bs3;
        }
    
        private void BtnSave_Click(object sender, EventArgs e)
        {
          using (StreamWriter wrt = new StreamWriter(fileName))
            wrt.Write(JsonConvert.SerializeObject(Daten));
        }
    
        public class Data
        {
          public ObservableCollection<Data1> List1 = new ObservableCollection<Data1>();
          public List<Data2> List2 = new List<Data2>();
          public List<Data3> List3 = new List<Data3>();
        }
    
        public class Data1
        {
          public int id { get; set; }
          public string Info1 { get; set; }
        }
        public class Data2
        {
          public int id { get; set; }
          public string Info2 { get; set; }
        }
        public class Data3
        {
          public int id { get; set; }
          public string Info3 { get; set; }
        }
      }
    }


    --
    Best Regards / Viele Grüße
    Peter Fleischer (former MVP for Developer Technologies)
    Homepage, Tipps, Tricks

    Montag, 29. April 2019 08:21

Alle Antworten

  • Hi,

    ich nehmen mal an, du hast eine WinForms Anwendung. Prinzipiell solltest du nicht die DGV's speichern oder deren Inhalt. Es wäre besser die Daten in einer oder in deinem Fall, mehreren Collection zu halten und an die DGV zu binden und die Datenquellen zu speichern/laden. Dazu gibt es viele Techniken: JSON, XML, CSV, Datenbank... Für einzelne Anwendungen mit überschaubaren Mengen an Daten ist JSON mein Favorit. Die Daten können dann recht leicht de/serialisiert werden.

    Gruß


    Freiberufler im Bereich Softwareentwicklung Von der PLC und Robotik zu VB.NET & C#, vorrangig WPF und UWP

    Sonntag, 28. April 2019 20:09
  • Hallo,

    Danke für deine Nachricht!

    Wir könnte sowas denn aussehen, im JSON Format für die 3 DGV's?

    Könntest du mir vielleicht ein Beispiel liefern?

    Sonntag, 28. April 2019 20:16
  • Kann ich...

    Hab mal ein "Minimal-Beispiel" gebastelt.

    Eine Form mit 3 DatagridView und der Code:

    Form:

    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsAppDataGridJsonSample
    {
        public partial class Form1 : Form
        {
            private const string FileName = @"C:\Temp\testDaten.json";
    
            private Data DataCollection;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                if (File.Exists(FileName))
                {
                    DataCollection = Json.ReadFromJsonFile<Data>(FileName);
                }
                else
                {
                    DataCollection = new Data();
                }
                dataGridView1.DataSource = DataCollection.DataTab1;
                dataGridView2.DataSource = DataCollection.DataTab2;
                dataGridView3.DataSource = DataCollection.DataTab3;
    
            }
    
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                Json.WriteToJsonFile<Data>(FileName, DataCollection);
            }
    
        }
    
        public class Data
        {
            public Data()
            {
                DataTab1 = new BindingList<DataTab1>();
                DataTab2 = new BindingList<DataTab2>();
                DataTab3 = new BindingList<DataTab3>();
            }
            public BindingList<DataTab1> DataTab1;
            public BindingList<DataTab2> DataTab2;
            public BindingList<DataTab3> DataTab3;
        }
    }

    DataModel:

    namespace WindowsFormsAppDataGridJsonSample
    {
        public class DataTab1
        {
            public DataTab1()
            {
                
            }
            public override string ToString() => $"{Column1};{Column2};{Column3}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
        }
    
        public class DataTab2
        {
            public DataTab2()
            {
    
            }
            public override string ToString() => $"{Column1};{Column2};{Column3};{Column4}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public string Column4 { get; set; }
        }
    
        public class DataTab3
        {
            public DataTab3()
            {
    
            }
            public override string ToString() => $"{Column1};{Column2};{Column3};{Column4};{Column5}";
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public string Column4 { get; set; }
            public string Column5 { get; set; }
        }
    }

    Json Serialisierung/Deserialisierung:

    using System.IO;
    
    namespace WindowsFormsAppDataGridJsonSample
    {
        public static class Json
        {
            /// <summary>
            /// Writes the given object instance to a Json file.
            /// <para>Object type must have a parameterless constructor.</para>
            /// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
            /// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
            /// </summary>
            /// <typeparam name="T">The type of object being written to the file.</typeparam>
            /// <param name="filePath">The file path to write the object instance to.</param>
            /// <param name="objectToWrite">The object instance to write to the file.</param>
            /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
            public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
            {
                TextWriter writer = null;
                try
                {
                    var contentsToWriteToFile = Newtonsoft.Json.JsonConvert.SerializeObject(objectToWrite);
                    writer = new StreamWriter(filePath, append);
                    writer.Write(contentsToWriteToFile);
                }
                finally
                {
                    try
                    {
                        if (writer != null)
                            writer.Close();
                    }
                    catch { }
                }
            }
    
            /// <summary>
            /// Reads an object instance from an Json file.
            /// <para>Object type must have a parameterless constructor.</para>
            /// </summary>
            /// <typeparam name="T">The type of object to read from the file.</typeparam>
            /// <param name="filePath">The file path to read the object instance from.</param>
            /// <returns>Returns a new instance of the object read from the Json file.</returns>
            public static T ReadFromJsonFile<T>(string filePath) where T : new()
            {
                TextReader reader = null;
                try
                {
                    reader = new StreamReader(filePath);
                    var fileContents = reader.ReadToEnd();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(fileContents);
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }
            }
        }
    }

    Und hier das kleine Projekt zum Download: https://1drv.ms/u/s!AlsOa7F9kTVPrtBuclruRDDhyTLkpQ

    Gruß


    Freiberufler im Bereich Softwareentwicklung Von der PLC und Robotik zu VB.NET & C#, vorrangig WPF und UWP


    Montag, 29. April 2019 08:01
  • Hi Stefan,
    hier mal eine kleine vollständige Demo von mir. Einfach den Code in eine leere Form kopieren:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
    
        private DataGridView dgv1 = new DataGridView() { Dock = DockStyle.Top };
        private DataGridView dgv2 = new DataGridView() { Dock = DockStyle.Top };
        private DataGridView dgv3 = new DataGridView() { Dock = DockStyle.Top };
        private Button btnLoad = new Button() { Text = "Load data", Dock = DockStyle.Top };
        private Button btnSave = new Button() { Text = "Save data", Dock = DockStyle.Top };
        private string fileName = @"c:\temp\DemoData.json";
        private Data Daten;
        private BindingSource bs1 = new BindingSource();
        private BindingSource bs2 = new BindingSource();
        private BindingSource bs3 = new BindingSource();
    
        private void Form03_Load(object sender, EventArgs e)
        {
          this.Controls.AddRange(new Control[] { dgv3, dgv2, dgv1, btnSave, btnLoad });
          this.btnLoad.Click += BtnLoad_Click;
          this.btnSave.Click += BtnSave_Click;
        }
    
        private void BtnLoad_Click(object sender, EventArgs e)
        {
          if (File.Exists(this.fileName))
          {
            using (StreamReader rdr = new StreamReader(fileName))
            Daten = JsonConvert.DeserializeObject<Data>(rdr.ReadToEnd());
          }
          else
          {
            this.Daten = new Data();
          }
          this.bs1.DataSource = Daten.List1;
          this.dgv1.DataSource = bs1;
          this.bs2.DataSource = Daten.List2;
          this.dgv2.DataSource = bs2;
          this.bs3.DataSource = Daten.List3;
          this.dgv3.DataSource = bs3;
        }
    
        private void BtnSave_Click(object sender, EventArgs e)
        {
          using (StreamWriter wrt = new StreamWriter(fileName))
            wrt.Write(JsonConvert.SerializeObject(Daten));
        }
    
        public class Data
        {
          public ObservableCollection<Data1> List1 = new ObservableCollection<Data1>();
          public List<Data2> List2 = new List<Data2>();
          public List<Data3> List3 = new List<Data3>();
        }
    
        public class Data1
        {
          public int id { get; set; }
          public string Info1 { get; set; }
        }
        public class Data2
        {
          public int id { get; set; }
          public string Info2 { get; set; }
        }
        public class Data3
        {
          public int id { get; set; }
          public string Info3 { get; set; }
        }
      }
    }


    --
    Best Regards / Viele Grüße
    Peter Fleischer (former MVP for Developer Technologies)
    Homepage, Tipps, Tricks

    Montag, 29. April 2019 08:21