xml反序列化并加载datagridview [英] xml deserialize and load datagridview

查看:106
本文介绍了xml反序列化并加载datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个xml文件并将其内容加载到datagridview中。通过阅读,我应该能够做一个简单的

I am trying to make an xml file and load the contents into a datagridview. From what I've read i should be able to do a simple

datagrid1.DataSource = cars;

但是由于某种原因,它在我的datagridview中没有显示任何内容。我正在试用此 answer 来查看是否可以使它正常工作。我不确定是否应该在此处发布所有代码,或者链接是否足够。如果需要,我可以在此处复制/粘贴该代码。

but for some reason it's not showing anything in my datagridview. I am using as a trial this answer to see if I can make it work. I wasn't sure if I should post all the code in here aswell or if the link is sufficient. If needed I can copy/paste that code here. If not can anyone point me in the right direction?

Class cars.cs

Class cars.cs

[Serializable()]
public class Car
{
 [System.Xml.Serialization.XmlElement("StockNumber")]
 public string StockNumber { get; set; }

 [System.Xml.Serialization.XmlElement("Make")]
 public string Make { get; set; }

 [System.Xml.Serialization.XmlElement("Model")]
 public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
  [XmlArray("Cars")]
  [XmlArrayItem("Car", typeof(Car))]
  public Car[] Car { get; set; }
}

表格

 private void Form1_Load(object sender, EventArgs e)
    {
        CarCollection cars = null;
        string path = "c://cars.xml";

        XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

        StreamReader reader = new StreamReader(path);
        cars = (CarCollection)serializer.Deserialize(reader);
        reader.Close();


        // finally bind the data to the grid
        dataGridView1.DataSource = cars;

    }


推荐答案

填充您需要设置数据源,然后获取数据(MSDN上的示例从数据库中获取,但xml源没有什么不同。我不确定是否看不到您的代码,但是您是否正在执行第二步?

To populate a datagridview you need to set the datasource and then get the data (example on MSDN shows getting from a database, but an xml source is not that different). Without seeing your code I'm not sure, but are you doing the second step?

SO答案应该可以解决您的问题。

This SO answer should solve your problem.

这篇关于xml反序列化并加载datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆