DropDownlist显示树状
啥都不说,直接上码...
/// <summary>
/// 绑定树视图
/// </summary>
/// <param name="dt">数据源</param>
private void BindTreeView(DataTable dt)
{
ddlCategorys.Items.Clear(); //清除数据
ddlCategorys.Items.Add(new ListItem("全部", "0"));
if (dt != null && dt.Rows.Count > 0)
{
DataRow[] nodeList = dt.Select("ParentID='0'");
for (int i = 0; i < nodeList.Length; i++)
{
ddlCategorys.Items.Add(new ListItem(nodeList[i][ddlCategorys.DataTextField].ToString(), nodeList[i][ddlCategorys.DataValueField].ToString()));
BindChildNode(dt, nodeList[i][ddlCategorys.DataValueField].ToString());
}
}
}
/// <summary>
/// 绑定子节点
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="parentValue">父值</param>
/// <param name="strBlank">分隔符</param>
private void BindChildNode(DataTable dt, string parentValue)
{
DataRow[] nodeList = dt.Select(string.Format(" {0} = '{1}' ", "ParentID", parentValue));
for (int i = 0; i < nodeList.Length; i++)
{
string strBlank = StringOfChar(int.Parse(nodeList[i]["Level"].ToString()), " ");
ddlCategorys.Items.Add(new ListItem(HttpUtility.HtmlDecode(strBlank) + nodeList[i][ddlCategorys.DataTextField].ToString(), nodeList[i][ddlCategorys.DataValueField].ToString()));
BindChildNode(dt, nodeList[i][ddlCategorys.DataValueField].ToString());
}
}
private string StringOfChar(int strLong, string str)
{
string ReturnStr = string.Empty;
if (strLong > 1)
{
for (int i = 1; i < strLong; i++)
{
ReturnStr += str;
}
ReturnStr += "├";
}
return ReturnStr;
}
/// 绑定树视图
/// </summary>
/// <param name="dt">数据源</param>
private void BindTreeView(DataTable dt)
{
ddlCategorys.Items.Clear(); //清除数据
ddlCategorys.Items.Add(new ListItem("全部", "0"));
if (dt != null && dt.Rows.Count > 0)
{
DataRow[] nodeList = dt.Select("ParentID='0'");
for (int i = 0; i < nodeList.Length; i++)
{
ddlCategorys.Items.Add(new ListItem(nodeList[i][ddlCategorys.DataTextField].ToString(), nodeList[i][ddlCategorys.DataValueField].ToString()));
BindChildNode(dt, nodeList[i][ddlCategorys.DataValueField].ToString());
}
}
}
/// <summary>
/// 绑定子节点
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="parentValue">父值</param>
/// <param name="strBlank">分隔符</param>
private void BindChildNode(DataTable dt, string parentValue)
{
DataRow[] nodeList = dt.Select(string.Format(" {0} = '{1}' ", "ParentID", parentValue));
for (int i = 0; i < nodeList.Length; i++)
{
string strBlank = StringOfChar(int.Parse(nodeList[i]["Level"].ToString()), " ");
ddlCategorys.Items.Add(new ListItem(HttpUtility.HtmlDecode(strBlank) + nodeList[i][ddlCategorys.DataTextField].ToString(), nodeList[i][ddlCategorys.DataValueField].ToString()));
BindChildNode(dt, nodeList[i][ddlCategorys.DataValueField].ToString());
}
}
private string StringOfChar(int strLong, string str)
{
string ReturnStr = string.Empty;
if (strLong > 1)
{
for (int i = 1; i < strLong; i++)
{
ReturnStr += str;
}
ReturnStr += "├";
}
return ReturnStr;
}
效果图:
数据源表结构: