I am trying to dynamically create a basic ASP.NET TreeView control. But when I call RenderControl() to get its output, ASP.NET throws null reference exceptions. What is ASP.NET doing behind the scenes when I declare a TreeView in .ascx/aspx that is NOT happening here?
Broken:
protected override void DoRender(HtmlTextWriter output)
{
TreeView treeview = new TreeView();
treeview.SkipLinkText = String.Empty; //omit this for exception on get_SpacerImageUrl
treeview.ImageSet = TreeViewImageSet.BulletedList;
TreeNode node = new TreeNode("Node 1");
node.ImageUrl = string.Empty;
node.ChildNodes.Add(new TreeNode("Subnode 1"));
node.ChildNodes.Add(new TreeNode("Subnode 2"));
treeview.Nodes.Add(node);
node = new TreeNode("Node 2");
node.ChildNodes.Add(new TreeNode("Subnode 1"));
node.ChildNodes.Add(new TreeNode("Subnode 2"));
node.ChildNodes.Add(new TreeNode("Subnode 3"));
treeview.Nodes.Add(node);
treeview.RenderControl(output);
}
Works fine:
<asp:TreeView ID="tvMenu" runat="server">
<Nodes>
<asp:TreeNode Text="Node 1">
<asp:TreeNode Text="Section 1"></asp:TreeNode>
<asp:TreeNode Text="Section 2"></asp:TreeNode>
<asp:TreeNode Text="Section 3"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Node 2">
<asp:TreeNode Text="Section One"></asp:TreeNode>
<asp:TreeNode Text="Section Two"></asp:TreeNode>
<asp:TreeNode Text="Section Three"></asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
The exception: [NullReferenceException: Object reference not set to an instance of an object.] System.Web.UI.WebControls.TreeView.GetImageUrl(Int32 index) +3089 System.Web.UI.WebControls.TreeNode.Render(HtmlTextWriter writer, Int32 position, Boolean[] isLast, Boolean enabled) +2329