Reputation: 2023
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;
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
[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; }
}
Form
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;
}
Upvotes: 1
Views: 4481
Reputation: 2023
sorry figured it out I had to do this:
dataGridView1.DataSource = cars.Car;
Upvotes: 0
Reputation: 9061
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?
This SO answer should solve your problem.
Upvotes: 1