当我运行我的程序并多次单击第二个选项卡时,它会创建标签x次,并且我不确定他们是否只能读取一次xml ...我尝试使用.close方法但是这对我不起作用...任何帮助将不胜感激谢谢
private void tabPage2_Enter(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabPage2)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("xmldoc.xml");
foreach (XmlNode node in xmlDoc.SelectNodes("check/tick/mark"))
{
Label l = new Label();
System.Drawing.Point l1 = new System.Drawing.Point(65, 48 + a);
l.Location = l1;
l.Text = node.SelectSingleNode("score").InnerText;
tabPage2.Controls.Add(l);
a += 25;
}
}
}
答案 0 :(得分:2)
在不同的函数中读取xml。创建一个变量来存储您是否已经读取了xml。只有在尚未调用xml读取函数时才调用它。
答案 1 :(得分:0)
这是因为您的代码读取了多次相同的xmldocument,所以请尝试:
bool read = false;
void ReadXmDocument()
{
using(XmlDocument xmlDoc = new XmlDocument())
{
xmlDoc.Load("xmldoc.xml");
foreach (XmlNode node in xmlDoc.SelectNodes("check/tick/mark"))
{
Label l = new Label();
System.Drawing.Point l1 = new System.Drawing.Point(65, 48 + a);
l.Location = l1;
l.Text = node.SelectSingleNode("score").InnerText;
tabPage2.Controls.Add(l);
a += 25;
}
read = true;
}
}
private void tabPage2_Enter(object sender, EventArgs e)
{
if(tabControl1.SelectedTab == tabPage2 && read == false) ReadXmlDocument();
}