Reputation: 37
I've been looking everywhere for how to do this but can't find anything that works. I have an application where you have a datagridview and add data using a textbox. i can successfully save the info to a XML file but can't load it:
Here is my code:
private void button1_Click(object sender, EventArgs e)// Save
{
DataTable dt2 = new DataTable("NewTable");
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dt2.Columns.Add(column.Name, column.ValueType);
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
DataGridViewRow row = dataGridView1.Rows[i];
DataRow newRow = dt2.Rows.Add();
for (int j = 0; j < row.Cells.Count; j++)
{
newRow[j] = row.Cells[j].Value;
}
}
dt2.WriteXml(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\_GridData_\test.xml", XmlWriteMode.WriteSchema);
}
Upvotes: 1
Views: 6297
Reputation: 21
string filePath =@"c:\data.xml";
DataSet dataSet = new DataSet();
//Read xml to dataset and pass file path as parameter
dataSet.ReadXml(filePath );
dataGridView.DataSource = dataSet.Tables[0];
Upvotes: 2
Reputation:
//Create xml reader
XmlReader xmlFile = XmlReader.Create("fullPathToYourXmlFile.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
//Read xml to dataset
dataSet.ReadXml(xmlFile);
//Pass empdetails table to datagridview datasource
dataGridView.DataSource = dataSet.Tables["empdetails"];
//Close xml reader
xmlFile.Close();
xmlFile.Close();
Upvotes: 1