單表 ArticlesGroup:GroupId (PK), GroupName, ParentId (FK 自關聯)。根節點 ParentId = 0。
private string _indent = "├";
private void BindCategories(string parentId)
{
using (var conn = new SqlConnection("server=.;database=test;uid=sa;pwd=;"))
using (var cmd = new SqlCommand(
"SELECT GroupId, GroupName FROM ArticlesGroup WHERE ParentId=@pid ORDER BY GroupName", conn))
{
cmd.Parameters.AddWithValue("@pid", parentId);
conn.Open();
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
string id = dr["GroupId"].ToString();
string name = dr["GroupName"].ToString();
DropDownList1.Items.Add(new ListItem(_indent + " " + name, id));
_indent += "─┴"; // 下一層縮進
BindCategories(id); // 遞迴處理子節點
_indent = _indent.Substring(0, _indent.Length - 2); // 回溯縮進
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategories("0");
DropDownList1.Items.Insert(0, new ListItem("Search All", "all"));
}
// 關鍵字輸入框焦點清空預設文字
keyword.Attributes["onfocus"] = "if(this.value=='key key key') this.value='';";
}
DataTable,記憶體中用 DataView.RowFilter 或 LINQ 篩選子節點。HttpRuntime.Cache),依賴 SqlCacheDependency 或檔案監視失效。