protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
this.Evaluate(dt);
Response.Write("原值输出<BR>");
Response.Write("ID ParentID Name<BR>");
Write(dt);
Response.Write("树形输出<BR>");
Response.Write("ID ParentID Name<BR>");
SetTree(dt, 1);
}
private void Evaluate(DataTable dt)
{
dt.Columns.Add("ID");
dt.Columns.Add("ParentID");
dt.Columns.Add("Name");
dt.Rows.Add(new object[] { 1, 0 , "商品"});
dt.Rows.Add(new object[] { 2, 1, "食品" });
dt.Rows.Add(new object[] { 3, 1, "电器" });
dt.Rows.Add(new object[] { 4, 2, "蔬菜" });
dt.Rows.Add(new object[] { 5, 2, "肉类" });
dt.Rows.Add(new object[] { 11, 3, "彩电" });
dt.Rows.Add(new object[] { 12, 3, "冰箱" });
dt.Rows.Add(new object[] { 13, 3, "洗衣机" });
dt.Rows.Add(new object[] { 6, 4, "白菜" });
dt.Rows.Add(new object[] { 7, 4, "萝卜" });
dt.Rows.Add(new object[] { 8, 5, "牛肉" });
dt.Rows.Add(new object[] { 9, 5, "羊肉" });
dt.Rows.Add(new object[] { 10, 5, "猪肉" });
//首先按ParentID升序排列
}
private void Write(DataTable dt)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Response.Write(dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString()
+ " " + dt.Rows[i][2].ToString() + "<BR>");
}
}
private void WriteLine(DataTable dt,int i)
{
Response.Write(dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString()
+ " " + dt.Rows[i][2].ToString() + "<BR>");
}
private void SetTree(DataTable dt,int iID)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToInt32(dt.Rows[i][1]) == iID)
{
SetTree(dt, Convert.ToInt32(dt.Rows[i][0]));
WriteLine(dt, i);
}
}
return;
}
效果如下,倒着输出了,稍做修改就正了。