要想实现无限级分类,那得还用传统的老方法----递归,也许有很多人会抱怨递归的性能不是太理想。俗话说的话,能抓到老鼠的猫就是好猫。我提倡先解决问题,然后再优化性能。
数据库结构:
代码:
protected void GetCategories(DropDownList DropDownList, string id)
{
DataView MyDataView = new Caicai.DBHelper().ExecuteDataSet("select id,c_name,c_path from c_categories where c_parentid=" + id +" order by c_sort").Tables["Table"].DefaultView;
foreach (DataRowView MyDataRowView in MyDataView)
{
AddTo = new String(' ', (MyDataRowView[2].ToString().Split('|').Length - 1) * 2) + "└ ";
DropDownList.Items.Add(new ListItem(AddTo + MyDataRowView[1].ToString(), MyDataRowView[0].ToString()));
this.GetCategories(DropDownList,MyDataRowView[0].ToString());
}
}
{
DataView MyDataView = new Caicai.DBHelper().ExecuteDataSet("select id,c_name,c_path from c_categories where c_parentid=" + id +" order by c_sort").Tables["Table"].DefaultView;
foreach (DataRowView MyDataRowView in MyDataView)
{
AddTo = new String(' ', (MyDataRowView[2].ToString().Split('|').Length - 1) * 2) + "└ ";
DropDownList.Items.Add(new ListItem(AddTo + MyDataRowView[1].ToString(), MyDataRowView[0].ToString()));
this.GetCategories(DropDownList,MyDataRowView[0].ToString());
}
}
调用:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetCategories(DropDownList1,"0");
}
}
{
if (!IsPostBack)
{
this.GetCategories(DropDownList1,"0");
}
}

本文介绍了一种使用递归方法来实现无限级分类的技术方案。通过具体的代码示例展示了如何从数据库中获取分类信息,并将其展示为带有层级关系的下拉列表。此方法虽然可能在性能上有所牺牲,但能够有效地解决实际问题。
119

被折叠的 条评论
为什么被折叠?



