MSDN关于TreeView的介绍整理了一下
aspx
aspx.cs
// 向TreeView中动态添加节点
public void PopulateNode(Object sender, TreeNodeEventArgs e)
{
//根据点击的节点深度添加节点
switch (e.Node.Depth)
{
case 0:
//点击根节点,添加第一级子节点
PopulateCategories(e.Node);
break;
case 1:
//点击第一级节点,添加第二级子节点
PopulateProducts(e.Node);
break;
default:
break;
}
}
///
/// 添加第一级子节点
///
///
private void PopulateCategories(TreeNode node)
{
DataSet ResultSet = RunQuery("Select CategoryID, CategoryName From Categories");
//建立第一级子节点
if (ResultSet.Tables.Count > 0)
{
//将DataSet每一行结果循环添加到父节点下
foreach (DataRow row in ResultSet.Tables[0].Rows)
{
//创建新节点,CategoryId为节点的value属性值
TreeNode NewNode = new TreeNode(row["CategoryName"].ToString(), row["CategoryID"].ToString());
//将PopulateOnDemand属性设置为true,可以在此节点下继续添加节点
NewNode.PopulateOnDemand = true;
//选中节点时引发TreeNodeExpanded事件
NewNode.SelectAction = TreeNodeSelectAction.Expand;
//TreeNodeSelectAction.None; TreeNodeSelectAction.Select; TreeNodeSelectAction.SelectExpand;
//添加节点
node.ChildNodes.Add(NewNode);
}
}
}
///
/// 添加第二级子节点
///
///
private void PopulateProducts(TreeNode node)
{
DataSet ResultSet = RunQuery("Select ProductName From Products Where CategoryID=" + node.Value);
// 建立第二级子节点
if (ResultSet.Tables.Count > 0)
{
//将DataSet每一行结果循环添加到第一级子节点下
foreach (DataRow row in ResultSet.Tables[0].Rows)
{
//创建新节点,节点的value未赋值,若还有第三级子节点,则必须赋值
TreeNode NewNode = new TreeNode(row["ProductName"].ToString());
//将PopulateOnDemand属性设置为false,则可以在此节点下继续添加节点,若需要继续添加,需设为true
NewNode.PopulateOnDemand = false;
//选中节点不引发任何事件
NewNode.SelectAction = TreeNodeSelectAction.None;
// Add the new node to the ChildNodes collection of the parent node.
node.ChildNodes.Add(NewNode);
}
}
}
///
/// 查询
///
///
///
private DataSet RunQuery(String QueryString)
{
String ConnectionString = "server = .; database = Northwind; uid = sa; pwd = 123456Aa;";
SqlConnection DBConnection = new SqlConnection(ConnectionString);
SqlDataAdapter DBAdapter;
DataSet ResultsDataSet = new DataSet();
try
{
DBAdapter = new SqlDataAdapter(QueryString, DBConnection);
DBAdapter.Fill(ResultsDataSet);
DBConnection.Close();
}
catch (Exception ex)
{
if (DBConnection.State == ConnectionState.Open)
{
DBConnection.Close();
}
}
return ResultsDataSet;
}