遞迴實現DropDownList層級
/// <summary>
/// 繫結下拉框(分層級)
/// </summary>
/// <param name="dt">繫結的資料來源</param>
/// <param name="parentId">上一級的ID名稱(資料列名稱)</param>
/// <param name="colId">下拉框值</param>
/// <param name="colName">下拉框顯示文字</param>
/// <param name="drs">頂級集合</param>
/// <param name="ddl">下拉框ID</param>
/// <param name="leveStr">層級的字首</param>
/// <param name="nextStr">多層級的字首</param>
protected void GetChild(DataTable dt, string parentId, string colId, string colName, DataRow[] drs, DropDownList ddl, string leveStr, string nextStr)
{
foreach (DataRow dr in drs)
{
string txt = dr[colName].ToString();
if (leveStr.Length != 1)
{
txt = leveStr + dr[colName].ToString();
}
ddl.Items.Add(new ListItem(txt, dr[colId].ToString()));
DataRow[] cdrs = dt.Select("n_parent_block_id=" + dr[colId]);
if (cdrs.Length != 0)
{
string nextLevelStr = leveStr.Insert(0, nextStr);
//string nextLevelStr = leveStr.Insert(0, "├");
GetChild(dt, parentId, colId, colName, cdrs, nextLevelStr, nextStr);
}
}
}
這段程式碼呼叫方法:
DataTable dt = new APP_BLOCKAUTHBLL().GetListByCondition("", "1", this.Name, CodeBin.StaticData.Curopuser.C_User_Name);
DataRow[] dr = dt.Select("n_parent_block_id=0");
GetChild(dt, "0", "n_block_id", "c_block_name", dr,"—", "—");
此處實現了多層級的表現方式,滿足需求,可以無限級,至於字首可以更改的