[英]Read/Load xml file by form loading using c#
我正在編寫一個程序,該程序將項目添加到DataGridView
並將輸入保存到通過單擊按鈕(如果不存在)創建的xml文件中。 這很好。 但是,如果我重新啟動程序,則應將每個項目加載到DataGridView
。 但是我必須先添加一個新項目,然后顯示所有其他項目。 因此,如果Form1加載,則這些項目將不會加載。 我想我必須在Form1_Load()
放入一些代碼,但是我沒有想法。 我試圖放XElement.Load();
在Form1_Load()
但沒有成功。 在這里您可以看到我的代碼:
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;
}
有人有想法或可以給我提示嗎?
提前致謝
干杯
您必須將其放在form1_load方法中:
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(@"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
我現在已經創建了您的應用,這是我的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;
}
當我運行應用程序時,我的datagrid充滿了xml數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.