winform下树和数据库关联操作是很常用的,下面的代码是项目中用到的,从一个表生成树:
两个相关的链结:《树形结构在开发中的应用》,
选择树节点,显示它的详细信息
DataView dvTree;
private void InitTreeByDataSet( TreeNodeCollection nds, string parentID, DataSet ds )
{
dvTree = new DataView();
TreeNode tempNode;
dvTree.Table = ds.Tables[0];
//判断ParentServiceTypeID是否为null,并生成不同的过滤条件
if ( parentID == "Isnull(ParentServiceTypeID,'Null Column') = 'Null Column'" )
{
dvTree.RowFilter = parentID ;
}
else
{
dvTree.RowFilter = "ParentServiceTypeID ='" + parentID +"'";
}
foreach ( DataRowView drvTree in dvTree )
{
tempNode = new TreeNode();
tempNode.Text = drvTree["Name"].ToString();
tempNode.Tag = drvTree["PKFieldValue"].ToString();
nds.Add(tempNode );
//递归调用
InitTreeByDataSet( tempNode.Nodes, tempNode.Tag.ToString(), ds );
}
}
private void InitTreeByDataSet( TreeNodeCollection nds, string parentID, DataSet ds )
{
dvTree = new DataView();
TreeNode tempNode;
dvTree.Table = ds.Tables[0];
//判断ParentServiceTypeID是否为null,并生成不同的过滤条件
if ( parentID == "Isnull(ParentServiceTypeID,'Null Column') = 'Null Column'" )
{
dvTree.RowFilter = parentID ;
}
else
{
dvTree.RowFilter = "ParentServiceTypeID ='" + parentID +"'";
}
foreach ( DataRowView drvTree in dvTree )
{
tempNode = new TreeNode();
tempNode.Text = drvTree["Name"].ToString();
tempNode.Tag = drvTree["PKFieldValue"].ToString();
nds.Add(tempNode );
//递归调用
InitTreeByDataSet( tempNode.Nodes, tempNode.Tag.ToString(), ds );
}
}
两个相关的链结:《树形结构在开发中的应用》,
选择树节点,显示它的详细信息