C#(XML)向DataGridViews添加列表

时间:2017-02-02 21:36:35

标签: c# xml serialization xml-serialization xmlserializer

它已将它们都添加到XML文件中,但是当我尝试在单独的网格上读取它们时,它会出现以下错误:未处理的类型' System.InvalidOperationException'发生在System.Xml.dll。

private void button1_Click(object sender, EventArgs e)
{
    List<person> p1 = new List<person>();
    List<murder> p2 = new List<murder>();
    XmlSerializer serial = new XmlSerializer(typeof(List<person>));
    XmlSerializer serial2 = new XmlSerializer(typeof(List<murder>));
    p1.Add(new person() { crimeid = 1, Name = "Bill" , location = "reading rg2 4qf" , stolen = "Sweets", date = "27/11/2017", evidence = "CCTV and eye witness", victim = "Tesco" });
    p2.Add(new murder() { crimeid = 1, name = "jerry springer", date = "04/05/2017", evidence = "weapons and statmnts", weaponused = "Knife", officeratsceneofthecrime = "Officer bill Clinton", timeofdeath = " 13:11",location = "london road", victimsname = "Gabe Gillen" });

    using (FileStream fs = new FileStream(Environment.CurrentDirectory+"\\people.xml",FileMode.Create,FileAccess.Write))
    {
       serial2.Serialize(fs, p2);
       serial.Serialize(fs, p1);
       MessageBox.Show("File Created");           
    }
}

private void button2_Click(object sender, EventArgs e)
{
   List<murder> p2 = new List<murder>();
   List<person> p1 = new List<person>();
   XmlSerializer serial2 = new XmlSerializer(typeof(List<murder>));
   XmlSerializer serial = new XmlSerializer(typeof(List<person>));

    using (FileStream fs = new FileStream(Environment.CurrentDirectory + "\\people.xml", FileMode.Open, FileAccess.Read))
    {
       p2 = serial2.Deserialize(fs) as List<murder>;
       p1 = serial.Deserialize(fs) as List<person>;
    }
    dataGridView1.DataSource = p1;
    dataGridView2.DataSource = p2;
}

0 个答案:

没有答案