namespace BQ_TreeView
{/// <summary>
/// BQ_TreeView 的摘要说明
/// </summary>
public class BQ_TreeView : System.Windows.Forms.TreeView
{
private System.ComponentModel.Container components = null;
private DataTable m_tb=null;
private string m_RootMatID;
BQ_TreeNode RootNode=null;
ArrayList alNode=new ArrayList ();
public BQ_TreeView()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
/// <summary>
///定义数据源
/// </summary>
public DataTable TreeDataSource
{
set
{
m_tb=value;
}
}
/// <summary>
///清空所有树控件中的信息
/// </summary>
private void clear()
{
if(RootNode!=null)
{
RootNode.Nodes .Clear ();
if(RootNode!=null)
{
try
{
RootNode.Remove ();
}
catch
{}
}
}
if(alNode!=null)
if(alNode.Count >0)
alNode.Clear ();
}
/// <summary>
/// 构造树控件
/// </summary>
public void MakeTree()
{
clear();//清除树节点中的资源
Cursor.Current =Cursors.WaitCursor ;
// 首先要给根节点付值,因为取出来的结构中没有根节点的信息
RootNode=new BQ_TreeNode(m_RootMatID);
RootNode.MatID =m_RootMatID;
alNode.Add(RootNode);
this.Nodes .Add (RootNode);
foreach(DataRow row in m_tb.Rows )
{
BQ_TreeNode FNode=null;
BQ_TreeNode CNode=null;
CNode=MakeArray(row["ID"].ToString (),row["物料编码"].ToString (),out FNode);
FNode.Nodes.Add (CNode);
}
RootNode.Expand ();
Cursor.Current =Cursors.Default ;
}
// <summary>
/// 构造一个动态数组,模拟树控件一个分叉的线性结构,每一次都是最新的线性结构,这整个控件关键地方
/// </summary>
/// <param name="strID">层次</param>
/// <param name="MatID">物料编码</param>
/// <param name="nodeF">父节点</param>
/// <returns>构造的节点</returns>。
private BQ_TreeNode MakeArray(string strID,string MatID,out BQ_TreeNode nodeF) {
try
{
BQ_TreeNode node=new BQ_TreeNode (MatID);
node.MatID =MatID;
BQ_TreeNode nodeRet=null;
int nGrade=int.Parse (strID);
if(nGrade==0)
{
}
else
{
if(alNode.Count>=nGrade+1)
{
alNode[nGrade]=node;
nodeRet=(BQ_TreeNode)alNode[nGrade-1];
}
else
{
alNode.Add (node);
nodeRet=(BQ_TreeNode)alNode[nGrade-1];
}
}
nodeF=nodeRet;
return node;
}
catch(Exception e)
{
throw new Exception("",e);
}
}
public string RootMatID
{
get
{
return m_RootMatID;
}
set
{
m_RootMatID=value;
}
}
}
}
经过编译就可以把控件BQ_TreeView添加进来,如下图(图2)
在应用程序中只要编写
bQ_TreeView1.RootMatID=strRootID;
bQ_TreeView1.TreeDataSource=tbProInfo;
bQ_TreeView1.MakeTree();
就可以显示整个BOM结构,tbProInfo为上面的Sql语句取出的表结构
希望本文对于有同样需求的朋友有所帮助,有空再给大家实现SQLSver,我的Email:gangleader@126.com