我正在尝试动态创建一个基本的ASP.NET TreeView控件。但是当我调用RenderControl()来获取其输出时,ASP.NET会抛出空引用异常。当我在.ascx / aspx中声明一个没有发生的TreeView时,ASP.NET在幕后做什么?
断裂:
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);
}
工作正常:
<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>
例外情况: [NullReferenceException:对象引用未设置为对象的实例。] System.Web.UI.WebControls.TreeView.GetImageUrl(Int32 index)+3089 System.Web.UI.WebControls.TreeNode.Render(HtmlTextWriter writer,Int32 position,Boolean [] isLast,Boolean enabled)+2329
答案 0 :(得分:0)
您可以在CodeBehind中创建动态TreeView控件,如下所示:
using (var db = new FORMS())
{
//Get Chapters from selected form
var query = from b in db.CHAPTERS
select b;
//Create treeview hierarchy
foreach (var rootItem in query)
{
TreeNode myNode = new TreeNode(rootItem.titulo, rootItem.id.ToString());
var childQuery = from b in db.SECTIONS
select b;
//Add childs
foreach (var childItem in childQuery)
{
TreeNode myChildNode = new TreeNode(childItem.titulo, childItem.id.ToString());
myNode.ChildNodes.Add(myChildNode);
}
ChapterTreeView.Nodes.Add(myNode);
}
}