2014-02-07 72 views
0

我有一個自定義的ASP.NET樹視圖控件,它使用現有的MS樹視圖。我從存儲的IEnumerable創建並重新創建樹視圖(它在UpdatePanel中)。StackOverflowException遞歸ASP.NET樹視圖人口

一些項目被添加像這樣:

public void BuildTreeFromItemCollection() 
    { 
     BuildTreeFromItemCollection(this.Items, null); 
    } 

    public void BuildTreeFromItemCollection(IEnumerable<StoredItem> items, TreeNode parentNode) 
    { 

     IEnumerable<TreeviewItem> tvItems = items.Cast<TreeviewItem>(); 
     var nodes = tvItems.Where(x => parentNode == null ? int.Parse(x.Parent) <= 0 : x.Parent == parentNode.Value); 

     TreeNode childNode; 
     foreach (var i in nodes) 
     { 
      childNode = new TreeNode(i.Name, i.Value) 
      { 
       PopulateOnDemand = this.PopulateOnDemand 
      }; 

      if (parentNode == null) 
      { 
       TvHierarchy.Nodes.Add(childNode); 
      } 
      else 
      { 
       parentNode.ChildNodes.Add(childNode); 
      } 

      this.BuildTreeFromItemCollection(items, childNode); 
     } 
    } 

TreeNodePopulate是像這樣處理:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack && !Page.IsAsync) 
     { 
      DD.Items = null; 

      DD.Items.Add(new TreeviewItem("Choice 1", "4", "-1"));// = items; 
      DD.Items.Add(new TreeviewItem("something", "1", "-1")); 
      DD.Items.Add(new TreeviewItem("Europe", "2", "-1")); 
      DD.Items.Add(new TreeviewItem("pff", "3", "-1")); 
}} 

的控制是一個使用BuildTreeFromItemCollection()的OnLoad初始化,並在它加載

void TvHierarchy_TreeNodePopulate(object sender, TreeNodeEventArgs e) 
    { 

     this.EnsureChildControls(); 

     IEnumerable<StoredItem> childItems = NodePopulator(e.Node.Value); 
     foreach (StoredItem item in childItems) 
     { 
      TreeNode newNode = new TreeNode(item.Name, item.Value); 
      newNode.PopulateOnDemand = this.PopulateOnDemand; 
      e.Node.ChildNodes.Add(newNode); 
     } 

     this.Items.AddRange(childItems); 
    } 

並且此Func臨時附加到NodePopulator上:

private IEnumerable<StoredItem> ItemLoader(string val) 
    { 
     List<StoredItem> itemList = new List<StoredItem>(); 
     Random r = new Random(); 

     for (int i = 0; i <= 4; i++) 
     { 
      int rand = r.Next(10,100); 
      itemList.Add(new TreeviewItem("test " + rand.ToString(), rand.ToString(), val)); 
     } 

     return itemList; 
    } 

不幸的是,BuildTreeFromItemCollection陷入無限循環幾個節點擴展後,周圍的4級,我離開堆棧溢出來的。

確切異常顯示出來就行了

var nodes = tvItems.Where(x => parentNode == null ? int.Parse(x.Parent) <= 0 : x.Parent == parentNode.Value); 

但是調用堆棧看起來已經填滿。問題在哪裏?

回答

0

如此看來,整個問題是代碼在這個測試函數生成新節點:

int rand = r.Next(10,100); 
itemList.Add(new TreeviewItem("test " + rand.ToString(), rand.ToString(), val)); 

所以生成的ID時已是前面的代碼進入無限循環。將範圍擴大到(10,10000)後,一切正常。