[英]Read/Load xml file by form loading using c#
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). 我正在编写一个程序,该程序将项目添加到
DataGridView
并将输入保存到通过单击按钮(如果不存在)创建的xml文件中。 This works fine. 这很好。 But if I restart the program it should load every item to
DataGridView
. 但是,如果我重新启动程序,则应将每个项目加载到
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.
因此,如果Form1加载,则这些项目将不会加载。 I think I have to put some code in
Form1_Load()
but I don't have an idea. 我想我必须在
Form1_Load()
放入一些代码,但是我没有想法。 I tried to put XElement.Load();
我试图放
XElement.Load();
in Form1_Load()
but no success. 在
Form1_Load()
但没有成功。 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 干杯
You will have to put this in the form1_load method: 您必须将其放在form1_load方法中:
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: 我现在已经创建了您的应用,这是我的Form1_Load方法:
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. 当我运行应用程序时,我的datagrid充满了xml数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.