如何将DataTable 绑定到TreeView-CSDN论坛

2024-12-01 10:37:53
推荐回答(1个)
回答(1):

将下面的方法添加到页代码中。
void PopulateCategories(TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand(
"Select CategoryName, CategoryID From Categories");
DataSet resultSet;
resultSet = RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
TreeNode NewNode = new
TreeNode(row["CategoryName"].ToString(),
row["CategoryID"].ToString());
NewNode.PopulateOnDemand = true;
NewNode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(NewNode);
}
}
}

将下面的方法添加到页代码中
void PopulateProducts(TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand();
sqlQuery.CommandText = "Select ProductName From Products " +
" Where CategoryID = @categoryid";
sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value =
node.Value;
DataSet ResultSet = RunQuery(sqlQuery);
if (ResultSet.Tables.Count > 0)
{
foreach (DataRow row in ResultSet.Tables[0].Rows)
{
TreeNode NewNode = new
TreeNode(row["ProductName"].ToString());
NewNode.PopulateOnDemand = false;
NewNode.SelectAction = TreeNodeSelectAction.None;
node.ChildNodes.Add(NewNode);
}
}
}