TreeView绑定数据库数据
TreeView控件可以通过递归方式绑定数据库数据,代码如下:
void Page_Load()
{
if (!Page.IsPostBack)
PopulateTreeView();
}
private void PopulateTreeView()
{
DataTable treeViewData = GetTreeViewData();
AddTopTreeViewNodes(treeViewData); //绑定父节点
}
private DataTable GetTreeViewData() //获取数据
{
string selectCommand = "SELECT MessageId,ParentId,Subject FROM Discuss";
string conString = WebConfigurationManager.ConnectionStrings["Discuss"].ConnectionString;
SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);
DataTable dtblDiscuss = new DataTable();
dad.Fill(dtblDiscuss);
return dtblDiscuss;
}
private void AddTopTreeViewNodes(DataTable treeViewData)
{
DataView view = new DataView(treeViewData);
view.RowFilter = "ParentID IS NULL";
foreach (DataRowView row in view)
{
TreeNode newNode = new TreeNode(row["Subject"].ToString(), row["MessageId"].ToString());
TreeView1.Nodes.Add(newNode);
AddChildTreeViewNodes(treeViewData, newNode);//绑定子节点
}
}
private void AddChildTreeViewNodes(DataTable treeViewData, TreeNode parentTreeViewNode)
{
DataView view = new DataView(treeViewData);
view.RowFilter = "ParentID=" + parentTreeViewNode.Value;
foreach (DataRowView row in view)
{
TreeNode newNode = new TreeNode(row["Subject"].ToString(), row["MessageId"].ToString());
parentTreeViewNode.ChildNodes.Add(newNode);
AddChildTreeViewNodes(treeViewData, newNode);//递归,绑定子节点
}
}
数据表中记录通过ParentId字段指定父节点。
详细介绍可以参考:《ASP.NET2.0揭秘卷1》
树节点TreeNode的重要属性:
Text:节点显示内容
Value:节点对应值
NavigateUrl:导航页面Url
Target:目标框架
ImageUrl:节点图像