Reputation: 133
I am facing "Out of Memory" issue when I am populating TreeView hierarchy using XML. Our XML structure is very complex and it is not in fix format. There are multiple level of child nodes. I am using recursion to iterate XML and populate TreeView structure. I tried to call GC.Collect. to clear memory but still it is throwing same error. I am using C# of .NET framework 3.5 for development.
I will appreciate if you can help me to find solution for this.
I'm providing the Code, Which I'm using for populating the treeview, below
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
string attribute = "";
treeView1.ImageList = imageList1;
treeViewResponse.ImageList = imageList1;
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
foo.MoveToFollowing(XPathNodeType.Element);
namespaces1 = foo.GetNamespacesInScope(XmlNamespaceScope.All);
if (xmlNode.HasChildNodes)
{
treeNode.ImageIndex = 0;
treeNode.SelectedImageIndex = 0;
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x++)
{
xNode = xmlNode.ChildNodes[x];
treeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = treeNode.Nodes[x];
//treeNode.Nodes[x].ImageIndex = -1;
addTreeNode(xNode, tNode);
}
}
else
{
treeNode.ImageIndex = 1;
treeNode.NodeFont = new Font("Arial", 8, FontStyle.Bold);
treeNode.SelectedImageIndex = 1;
treeNode.Text = xmlNode.OuterXml.Trim();
}
}
Upvotes: 3
Views: 2539
Reputation: 51
As Raymond suggested, you should construct the font one time and reuse it. I have noticed that even if you do this, changing node fonts immediately causes a redraw of the control which can cause TreeView to construct internal fonts in addition to the one you provided it. I have seen cases where this can cause the font handle usage to go up very fast such that the garbage collector does not free them fast enough. I think this is a bug in TreeView that is not very repeatable but will happen sometimes. A way to protect yourself against Treeview using all your application's GDI handles is to wrap a set of node adds or font changes in TreeView.BeginUpdate() and TreeView.EndUpdate() calls.
m_treeView.BeginUpdate();
try
{
// TreeNode adds changes here
}
finally
{
m_treeView.EndUpdate();
}
This will result in only one redraw even though you added or changed multiple nodes.
Steve
Upvotes: 5