2012-04-20 78 views
1

當我運行我的程序並多次單擊第二個選項卡時,它會創建標籤x次數,並且im不確定他們是否只能讀取xml一次...我試圖用一個.close方法,但沒有工作對我來說...任何幫助,將不勝感激謝謝當我讀取xml文件時,它讀取元素的重複項

 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; 
      } 
     } 
    } 

回答

2

執行XML在不同的功能讀書。創建一個變量來存儲您是否已經讀取了xml。如果尚未調用xml讀取函數,請調用它。

+0

嗯是啊,讓SENCE讓我給它一個鏡頭,感謝名單 – Hashey100 2012-04-20 13:02:02

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(); 
    }