Reputation: 3297
I'm writing a program which add items to DataGridView
and save the inputs to an xml file which is created by clicking button (if not exists). This works fine. But if I restart the program it should load every item to DataGridView
. But I have to add a new item first and then all the other items are displayed. So the items won't load if Form1 load. I think I have to put some code in Form1_Load()
but I don't have an idea. I tried to put XElement.Load();
in Form1_Load()
but no success. Here you can see my code:
XElement xmlFile;
XElement xmlnode;
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(@"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!File.Exists(@"C:\Users\rs\Desktop\Save\save.xml"))
{
using (File.Create(@"C:\Users\rs\Desktop\Save\save.xml")) { }
}
xmlnode = new XElement("iToDo",
new XElement("Name", txtName.Text),
new XElement("Priority", comPrio.Text),
new XElement("StartDate", txtStart.Text),
new XElement("EndDate", txtEnd.Text),
new XElement("Comment", txtComment.Text)
);
try
{
xmlFile = XElement.Load(@"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
catch (XmlException)
{
xmlFile = new XElement("ToDos", xmlnode);
}
xmlFile.Save(@"C:\Users\rs\Desktop\Save\save.xml");
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(@"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
Someone got an idea or can give me a hint?
Thanks in advance
Cheers
Upvotes: 0
Views: 1026
Reputation: 26
You will have to put this in the form1_load method:
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(@"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
I've created your app now, here's my Form1_Load method:
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(@"C:\save.xml");
xmlFile.Add(xmlnode);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(@"C:\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
When I run the app, then my datagrid gets filled with the xml data.
Upvotes: 1