要想实现无限级分类,那得还用传统的老方法----递归,也许有很多人会抱怨递归的性能不是太理想。俗话说的话,能抓到老鼠的猫就是好猫。我提倡先解决问题,然后再优化性能。
数据库结构:
代码:
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 " );
}
}