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];
}
这段是无限级树形的代码..可是我还想绑一个dropdownlist2.当dropdownlist一改变.dropodownlist就跟着改变.而且树形可以不手动绑数据吗?能直接调类文件.我是初学者希望大家帮下
参考:http://www.cnblogs.com/zgx/archive/2009/05/12/1455121.html
上面的方法是可行的。
你说的就是下拉列表联动的情况,可以将你需要binding到控件上的数据封装起来,然后给封装的方法传控件的Id和参数,就可以实现联动了,可以百度一下,园子里的示例也很多