我想製作一個xml文件並將內容加載到datagridview中。從我讀過的,我應該可以做一個簡單的xml反序列化並加載datagridview
datagrid1.DataSource = cars;
但由於某種原因它沒有顯示我的datagridview中的任何東西。我正在使用這個answer作爲試驗,看看我能否實現它。我不確定是否應該在這裏發佈所有代碼,或者鏈接是否足夠。如果需要,我可以在這裏複製/粘貼該代碼。如果沒有,任何人都可以指出我的方向?
類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;
}