protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable datatable = this.GetDataTable();
DataRow[] row = datatable.Select("ParentID=-1");
//添加根目录
for (int i = 0; i <= row.Length-1; i++)
{
ListItem li = new ListItem(row[i]["MajName"].ToString());
//ListItem li2 = new ListItem(row[1]["MajName"].ToString());
DropDownList1.Items.Add(li);
//DropDownList1.Items.Add(li2);
addOtherDll("", Convert.ToInt32(row[i]["MajID"]), datatable, 1);
}
}
}
/**/
/// <summary>
/// 添加其他节点
/// </summary>
/// <param name="Pading">空格</param>
/// <param name="DirId">父路径ID</param>
/// <param name="datatable">返回的datatable</param>
/// <param name="deep">树形的深度</param>
private void addOtherDll(string Pading, int DirId, DataTable datatable, int deep)
{
DataRow[] rowlist = datatable.Select("ParentID='" + DirId + "'");
foreach (DataRow row in rowlist)
{
string strPading = "";
for (int j = 0; j < deep; j++)
{
strPading += " "; //用全角的空格
}
//添加节点
ListItem li = new ListItem(strPading + "|--" + row["MajName"].ToString());
DropDownList1.Items.Add(li);
//递归调用addOtherDll函数,在函数中把deep加1
addOtherDll(strPading, Convert.ToInt32(row["MajID"]), datatable, deep + 1);
}
}
/**/
/// <summary>
/// 从数据库中读取数据返回datatable
/// </summary>
/// <returns></returns>
private DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ddltest"].ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter("select * from tblMajor", conn);
DataSet datset = new DataSet();
conn.Open();
adp.Fill(datset, "tblMajor");
return datset.Tables[0];
}
dropdownlist无限级联动要怎么取出里面的值的ID.能有人回答一下吗?
你这个程序是显示一个树形的下拉框吧。
ListItem 可以指定一个Value啊,
你的绑定代码ListItem li = new ListItem(strPading + "|--" + row["MajName"].ToString());可以更正为 ListItem li = new ListItem(strPading + "|--" + row["MajName"].ToString(),row["MajID"].ToString());
这样你在后台直接seletValue就可以得到选定节点的value 绑定的“MajID” 值。