gpt4 book ai didi

c# - 如何绘制迭代 ul-li 列表模式?

转载 作者:行者123 更新时间:2023-11-30 20:55:21 26 4
gpt4 key购买 nike

我想在预览中绘制 Html。

查看预览 click here .查看Source查看 ul -li 渲染的页面。为此,我写了一个如下所示的方法

private void DrawTree(HtmlGenericControl ParentULTag, int count)
{

for (int i = 0; i < count; i++)
{
HtmlGenericControl ChildLi = new HtmlGenericControl("li");
HtmlGenericControl ChildUl = new HtmlGenericControl("ul");
ChildLi.Controls.Add(ChildUl);
ParentULTag.Controls.Add(ChildLi);
ChildLi.InnerText = i.ToString();
DrawTree(ChildUl, i);
}
}

但是它是这样画的

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

我在页面加载中启动了方法,如图所示

HtmlGenericControl Initial = new HtmlGenericControl("ul"); 
DrawTree(Initial,4);

这段代码有什么错误?

最佳答案

试试这个:

    private static HtmlGenericControl GenerateList(int count)
{
HtmlGenericControl parent = new HtmlGenericControl("ul");
for (int i = 1; i <= count; i++)
{
HtmlGenericControl ChildLi = new HtmlGenericControl("li");
ChildLi.InnerText = i.ToString();
HtmlGenericControl ChildUl = new HtmlGenericControl("ul");
ChildLi.Controls.Add(ChildUl);
for (int j = 1; j <= i; j++) {
HtmlGenericControl FinalLi = new HtmlGenericControl("li");
FinalLi.InnerText = j.ToString();
ChildUl.Controls.Add(FinalLi);
}
parent.Controls.Add(ChildLi);
}
return parent;
}

编辑:

您应该将您的输入表示为树结构。这里我使用了一个 Node 对象,它有一个 IDChildren 属性:

class Node
{
public int ID { get; set; }
public Node[] Children { get; set; }
public Node(int id, Node[] children)
{
ID = id;
Children = children;
}
public Node(int id)
{
ID = id;
Children = new Node[] { };
}
}

class Program
{

public static HtmlGenericControl GetList(Node root)
{
HtmlGenericControl ul = new HtmlGenericControl("ul");
GetListImpl(root, ul);
return ul;
}

private static void GetListImpl(Node root, HtmlGenericControl rootElement)
{
foreach (var item in root.Children)
{
HtmlGenericControl li = new HtmlGenericControl("li");
li.InnerText = item.ID.ToString();
if (item.Children.Length > 0)
li.Controls.Add(GetList(item));

rootElement.Controls.Add(li);
}
}

public static string HtmlGenericControlToString(HtmlGenericControl control)
{
string contents = null;
using (System.IO.StringWriter swriter = new System.IO.StringWriter())
{
HtmlTextWriter writer = new HtmlTextWriter(swriter);
control.RenderControl(writer);
contents = swriter.ToString();
}
return contents;
}


static void Main(string[] args)
{
Node root = new Node(0,
new Node[]{
new Node(1, new Node[]{
new Node(1),
new Node(2)
}),
new Node(2, new Node[]{
new Node(1),
new Node(2, new Node[]{
new Node(1)
})
})
});
var ul = GetList(root);
var html = HtmlGenericControlToString(ul);
Console.WriteLine(html);
}
}

关于c# - 如何绘制迭代 ul-li 列表模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com