DataGridView Zapisywanie List do pliku Serializacja

Dyskusje na temat języka C# oraz biblioteki .NET
profit
Początkujący
Początkujący
Posty: 17
Dołączył(a): wtorek, 3 listopada 2015, 21:05

DataGridView Zapisywanie List do pliku Serializacja

Post przez profit »

Bardzo proszę o pomoc. Nie wiem jak poradzić sobie z pewnym problemem. Chodzi mi o zapisywanie do pliku dat czyli serializacje. Zamieszczam poniżej kod który czasami działa poprawnie(tak mi się wydaje) a czasami nie. Urachamia się i wczytuje dane do listy podane w kodzie i wyśietla. Teraz w datagridview edytuje dodaje usuwam itd. i zapisuje do pliku. I teraz gdy wczytuje dane z pliku do datagridview to czasami wczytuja się wszystkie dane poprawnie a czasmi po wczytaniu wyswietlaja się tylko dane te z kodu. Spedziłem dwa dni na poszukiwanie rozwiązania i niestety NIC!!

Code: Zaznacz cały

public partial class kontrahenci : Form
    {
 [Serializable]
    public class Kontrahent
    {
        public int Id
        {
            get
            {
              
                return id;
            }
            set
            {
                id = value;
            }
        }
        private int id;
        public string FirstName { get; set; }
        public string LastName { get; set; }
        

        List<Kontrahent> kontra = new List<Kontrahent>();

        public kontrahenci()
        {
            InitializeComponent();



            kontra.Add(new Kontrahent() { Id = 1, FirstName = "Michał", LastName = "Nowak});
            kontra.Add(new Kontrahent() { Id = 2, FirstName = "Monika", LastName = "Hanc" });
            kontra.Add(new Kontrahent() { Id = 3, FirstName = "Jan", LastName = "Kowalski" });
            kontra.Add(new Kontrahent() { Id = 4, FirstName = "Franek", LastName = "Zielichowski" });

        }

        private void kontrahenci_Load(object sender, EventArgs e)
        {

            
            bindingSource1.DataSource = kontra;
            dataGridView1.DataSource = bindingSource1;
            bindingNavigator1.BindingSource = bindingSource1;
            

        }
      
        private void button2_Click(object sender, EventArgs e)
        {
            //---------------Zapisywanie--------------
           
            if (File.Exists(@"c:\fakturka\kontrahenci.dat"))
            {
                File.Delete(@"c:\fakturka\kontrahenci.dat");
            }
            string path = @"c:\fakturka\kontrahenci.dat";
            using (Stream output = File.Create(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(output, kontra);
                MessageBox.Show("Lista kontrahentów zostala zapisana na dysku");

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //---------------Odczytywanie--------------
         
            string path = @"c:\fakturka\kontrahenci.dat";

            using (Stream input = File.OpenRead(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                List<Kontrahent> kontra = (List<Kontrahent>)formatter.Deserialize(input);

                bindingSource1.DataSource = kontra;
                dataGridView1.DataSource = bindingSource1;
                bindingNavigator1.BindingSource = bindingSource1;

                MessageBox.Show("Dane zostaly wczytane!");
            }
        }
Morfidon
Administrator
Administrator
Posty: 1332
Dołączył(a): wtorek, 5 sierpnia 2008, 21:48
Contact:

Re: DataGridView Zapisywanie List do pliku Serializacja

Post przez Morfidon »

Hej,

Prześlij cały projekt do testu. Niestety na pierwszy rzut oka ciężko mi coś znaleźć nieprawidłowego. Jak odpalę program pewnie szybciej znajdę błąd.

Pozdrawiam :)
profit
Początkujący
Początkujący
Posty: 17
Dołączył(a): wtorek, 3 listopada 2015, 21:05

Re: DataGridView Zapisywanie List do pliku Serializacja

Post przez profit »

Poczytałem trochę na temat serializacji do XML. I przerobiłem projekt do XML i teraz prawie wszystko działa. Prawie gdyż gdy odkomentuje wiersze kodu w InvoiceKlasy. Program nie wczytuje danych z pliku i przy próbie dodania nowej osoby wysypuje się.
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: No row can be added to a DataGridView control that does not have columns. Columns must be added first.
Nie rozumiem dlaczego dodanie konstruktora to powoduje???

plik klasy

Code: Zaznacz cały

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace Invoice
{

    public class Kontrahent
    {

        public int Id
        {
            get
            {
              
                return id;
            }

        }
        private int id;

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        private static int NextId = 1;

        //--------------------------Jeżeli to odkomentuje to nie działa---------------

        //public Kontrahent(string firstName, string lastName)
        //{
        //    NextId++;
        //    id = NextId;

        //    FirstName = firstName;
        //    LastName = lastName;

        //}




    }
   

    //------------Serializacja XML--------------
    class Serializacja
    {


        public static void XMLSerialize(List<Kontrahent> kontrahent)
        {

            StreamWriter sw = new StreamWriter(@"c:\fakturka\kontrahent.xml");
            try
            {
                XmlSerializer s = new XmlSerializer(typeof(List<Kontrahent>));
                s.Serialize(sw, kontrahent);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                sw.Close();
            }
        }
    }
    ///------------------Deserializacja XML-------------------
    class DeSerializacja
    {

        public static List<Kontrahent> XMLDeserialize(string xmlFile)
        {
            List<Kontrahent> obj;
            XmlReader xr = XmlReader.Create(xmlFile);
            try
            {
                XmlSerializer s = new XmlSerializer(typeof(List<Kontrahent>));
                obj = (List<Kontrahent>)s.Deserialize(xr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                obj = null;
            }
            finally
            {
                xr.Close();
            }
            return obj;
        }

    }
}
plik form

Code: Zaznacz cały

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Invoice
{
    public partial class Form1 : Form
    {
        private List<Kontrahent> kontrahent;

        

        public Form1()
        {
            InitializeComponent();
        //    kontrahent = new List<Kontrahent>();
           kontrahent = DeSerializacja.XMLDeserialize(@"c:\fakturka\kontrahent.xml");
         
           


        }

        private void button1_Click(object sender, EventArgs e)
        {
            ////-------------- Zapisywanie po nacisnieciu przycisku
            Serializacja.XMLSerialize(kontrahent);
          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            /////////// -----Deserializacja Wczytywanie po nacisnieciu przycisku

            kontrahent = DeSerializacja.XMLDeserialize(@"c:\fakturka\kontrahent.xml");
            bindingSource1.DataSource = kontrahent;
            dataGridView1.DataSource = bindingSource1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bindingNavigator1.BindingSource = bindingSource1;
            bindingSource1.DataSource = kontrahent;
            dataGridView1.DataSource = bindingSource1;
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Jest " + kontrahent.Count + " kontrahentów");
            
        }

        

        

      

        private void button4_Click(object sender, EventArgs e)
        {
            comboBox2.DataSource = kontrahent;
            comboBox2.DisplayMember = "FirstName";
            comboBox2.ValueMember = "LastName";
            

            
        }
    }
}

Post Reply