如下图的效果:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = GetCategory().Tables[0];
//绑定数据到栏目列表上
BindToChannelList(dt, 0);
}
}
/// <summary>
/// 递归绑定数据到ddlChannelList控件上,形成树状结构
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="categoryid">栏目id</param>
private void BindToChannelList(DataTable dt, int categoryid)
{
//DataView dv = dt.DefaultView;使用这句在asp.net 1.1中会出现"在位置 1 处没有任何行。"的错误,感谢阿耀同学的帮助.
DataView dv=new DataView(dt);
dv.RowFilter = " ParentID= " + categoryid.ToString(); //过滤
int layer = 0; //默认为第一层
foreach (DataRowView drv in dv)
{
layer = int.Parse(drv["Layer"].ToString().Trim()); //取得第几层
string span = "";
if (categoryid != 0)
{
for (int i = 0; i < layer; i++)
{
span += " ";
}
span += "|╴";//添加前面的空格
}
ListItem li = new ListItem();
li.Text = span + drv["CategoryName"].ToString();
li.Value = drv["CategoryID"].ToString();
this.ddlChannelList.Items.Add(li);
BindToChannelList(dt, Convert.ToInt32(drv["CategoryID"]));
}
}
----数据库表结构
CREATE TABLE [Category] (
[CategoryID] [int] IDENTITY (1, 1) NOT NULL ,
[CategoryName] [nvarchar] (255) NOT NULL ,
[Layer] [int] NULL DEFAULT (1),
[ParentID] [int] NULL DEFAULT (0),
[Intro] [nvarchar] (255) NULL ,
[AddTime] [datetime] NULL DEFAULT (getdate()),
CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED
(
[CategoryID]
) ON [PRIMARY]
) ON [PRIMARY]
GO