要实现下面的效果:
首先可实现DropDownList:
public void SetDDL(ref System.Web.UI.WebControls.DropDownList ddl, string value) { if (ddl != null) { if (ddl.Items.FindByValue(value) != null) { ddl.SelectedIndex = -1; ddl.Items.FindByValue(value).Selected = true; }
} }
具体实现的方法:
public void BindAccountTree(ref System.Web.UI.WebControls.DropDownList ddl, bool withEmptyItem) { int AccountID= -1;
ddl.Items.Clear(); Account rootAccount = AccountLogic.GetInstance().GetAccount(AccountID); ddl.Items.Add(new ListItem(rootAccount.Name, rootAccount.AccountID.ToString()));
AddChild(rootAccount.AccountID, ddl, 0);
if (withEmptyItem) { ListItem item = new ListItem("请选择...", ""); ddl.Items.Insert(0, item); } }
GetAccount 方法:
public Account GetAccount(int AccountID) //Get one Account {
string sqlCommand = "SELECT * FROM Account WHERE AccountID=" + AccountID;
}
AddChild方法:
private void AddChild(int ParentID, DropDownList ddl, int Level) { string strSpace = " "; IList list = AccountLogic.GetInstance().FetchSubAccounts(ParentID, "Name"); string strA = strSpace.Substring(0, Level + 1) + "|-";
Account account = null;
for (int i = 0; i < list.Count; i++) { account = (Account)list[i];
ddl.Items.Add(new ListItem(strA + account.Name, account.AccountID.ToString()));
if (Level > 20) break; AddChild(account.AccountID, ddl, Level + 1); } }
FetchSubAccounts方法:
public IList FetchSubAccounts(int AccountID, string Order) { IList Accounts = new ArrayList(); Database db = DatabaseFactory.CreateDatabase(); string sqlCommand = "SELECT * FROM Account ";
sqlCommand += (sqlCommand.IndexOf("WHERE") > 0 ? " AND" : " WHERE") + " (Deleted = 0)";
sqlCommand += " AND (ParentID=" + AccountID + ")";
if (Order.Trim().Length > 0) { sqlCommand += " ORDER BY " + Order;//Title DESC, Href } DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand); try { using (IDataReader dr = db.ExecuteReader(dbCommand)) { while (dr.Read()) { Accounts.Add(GetAccount(dr)); } } } catch (Exception ex) { Logging.WriteLog(ex); } return Accounts; }
页面调用方法:
private void BindParentAccount() { this.BindAccountTree(ref this.ddlAccount, true); }
数据库表结构: