【问题标题】:xml deserialize and load datagridviewxml反序列化并加载datagridview
【发布时间】:2011-12-12 00:08:42
【问题描述】:

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

datagrid1.DataSource = cars;

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

类汽车.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;

    }

【问题讨论】:

    标签: c# xml winforms datagridview


    【解决方案1】:

    要填充数据网格视图,您需要set the datasource and then get the data (example on MSDN shows getting from a database, but an xml source is not that different)。没有看到你的代码我不确定,但你在做第二步吗?

    这个SO answer 应该可以解决你的问题。

    【讨论】:

      【解决方案2】:

      抱歉,我不得不这样做:

       dataGridView1.DataSource = cars.Car;
      

      【讨论】:

        猜你喜欢
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 2012-03-04
        • 2011-03-03
        相关资源
        最近更新 更多