2012-12-06 27 views
0

我有一個XML文件,我正在加載並將文檔分解爲Ienumerable,然後將每個元素放入一個winform中的標籤。 SOFAR我有下面的代碼,其中工程需要從XML文件填充多個標籤,有沒有更快的方法?

public void PopulateGameBoard() 
    { 
     XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy); 

     IEnumerable<string> categories = 
      from category in gameFiles.Descendants("category") 
      select (string)category.Attribute("name"); 


     string first = categories.ElementAt(0); 
     cat1HeaderLabel.Text = first; 
     string second = categories.ElementAt(1); 
     cat2HeaderLabel.Text = second; 
     string third = categories.ElementAt(2); 
     cat3Label.Text = third; 
     string fourth = categories.ElementAt(3); 
     cat4Label.Text = fourth; 
     string fifth = categories.ElementAt(4); 
     cat5Label.Text = fifth; 

    } 

最終產品是危害遊戲板,其中的類別和問題會從XML文件

被拉這是第5行,我需要的(5個列表進入5行)做到這一點。我想知道是否有更好的方法來編寫代碼,我不會用25個語句分配一個變量到ElementAt(),然後分配25個變量。

回答

0

在這裏,我試圖動態創建標籤,並給它們賦值,這是一個手工編寫的代碼,所以沒有機制保障它將編譯,進行必要的更改

public void PopulateGameBoard() 
{ 
    XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy); 
    IEnumerable<string> categories = 
     from category in gameFiles.Descendants("category") 
     select (string)category.Attribute("name"); 
    Label[] cat1HeaderLabel= new Label[100]; 
    int i = 0; 
     categories.Each(p => 
     { 
      cat1HeaderLabel[i] = new Label(); 
      cat1HeaderLabel[i].Text = p; 
      this.Form.Controls.Add(cat1HeaderLabel[i]); 
      i++; 
     }); 
} 
相關問題