/// <summary>
/// 绑定一个表到树
/// </summary>
/// <param name="pDataTable">表</param>
/// <param name="pParentKeyCol">上级列名</param>
/// <param name="pKeyCol">key列名</param>
/// <param name="pTextCol">Text列名</param>
/// <param name="pAddTheseTopKey">要加入的节点,如果为Null,就加入顶层节点</param>
/// <returns></returns>
public void BindDataTable( DataTable pDataTable,string pParentKeyCol,string pKeyCol,string pTextCol,params string[] pAddTheseTopKey)
{
mDataTable=pDataTable;
mParentKeyCol=pParentKeyCol;
mKeyCol=pKeyCol;
mTextCol=pTextCol;
mAddTheseTopKey=pAddTheseTopKey;
try
{
this.Nodes.Clear() ; DataRow[] drvs;
if (pAddTheseTopKey!=null && pAddTheseTopKey.Length >0)
{
this.BeginUpdate ();
foreach(string topkey in pAddTheseTopKey)
{
drvs=mDataTable.Select( pKeyCol + "='" + topkey +"'");
foreach(DataRow drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),null);
}
}
else
{
drvs=mDataTable.Select( "Isnull(" + pParentKeyCol +",'') = ''",pParentKeyCol,DataViewRowState.CurrentRows ) ; //CurrentRows舍掉被删除的行
foreach(DataRow drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),null);
}
mFillByTable=true;
}
catch( System.Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex.Message );
}
finally
{
this.EndUpdate ();
}
}
/// <summary>
/// 加入一个Node,并加入其所有子树
/// </summary>
/// <param name="pText">文本</param>
/// <param name="Index">Node的上级</param>
private void AddNode(string pKey,string pText,TreeNode ptd)
{
try
{
System.Windows.Forms.TreeNodeCollection tds;
string oldSort=mDataTable.DefaultView.Sort ;
if (ptd==null)
tds=this.Nodes ;
else
{
tds=ptd.Nodes;
}
if (tds!=null)
{
TreeNode td=tds.Add (pText);
AllNodes.Add ((object)pKey,td);
mDataTable.DefaultView.Sort=mParentKeyCol;
DataRowView[] drvs=mDataTable.DefaultView.FindRows(pKey); //查子级
foreach(DataRowView drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),td); mDataTable.DefaultView.Sort=oldSort;
}
}
catch( System.Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex.Message );
} }
/// 绑定一个表到树
/// </summary>
/// <param name="pDataTable">表</param>
/// <param name="pParentKeyCol">上级列名</param>
/// <param name="pKeyCol">key列名</param>
/// <param name="pTextCol">Text列名</param>
/// <param name="pAddTheseTopKey">要加入的节点,如果为Null,就加入顶层节点</param>
/// <returns></returns>
public void BindDataTable( DataTable pDataTable,string pParentKeyCol,string pKeyCol,string pTextCol,params string[] pAddTheseTopKey)
{
mDataTable=pDataTable;
mParentKeyCol=pParentKeyCol;
mKeyCol=pKeyCol;
mTextCol=pTextCol;
mAddTheseTopKey=pAddTheseTopKey;
try
{
this.Nodes.Clear() ; DataRow[] drvs;
if (pAddTheseTopKey!=null && pAddTheseTopKey.Length >0)
{
this.BeginUpdate ();
foreach(string topkey in pAddTheseTopKey)
{
drvs=mDataTable.Select( pKeyCol + "='" + topkey +"'");
foreach(DataRow drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),null);
}
}
else
{
drvs=mDataTable.Select( "Isnull(" + pParentKeyCol +",'') = ''",pParentKeyCol,DataViewRowState.CurrentRows ) ; //CurrentRows舍掉被删除的行
foreach(DataRow drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),null);
}
mFillByTable=true;
}
catch( System.Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex.Message );
}
finally
{
this.EndUpdate ();
}
}
/// <summary>
/// 加入一个Node,并加入其所有子树
/// </summary>
/// <param name="pText">文本</param>
/// <param name="Index">Node的上级</param>
private void AddNode(string pKey,string pText,TreeNode ptd)
{
try
{
System.Windows.Forms.TreeNodeCollection tds;
string oldSort=mDataTable.DefaultView.Sort ;
if (ptd==null)
tds=this.Nodes ;
else
{
tds=ptd.Nodes;
}
if (tds!=null)
{
TreeNode td=tds.Add (pText);
AllNodes.Add ((object)pKey,td);
mDataTable.DefaultView.Sort=mParentKeyCol;
DataRowView[] drvs=mDataTable.DefaultView.FindRows(pKey); //查子级
foreach(DataRowView drv in drvs)
AddNode(drv[mKeyCol].ToString(),drv[mTextCol].ToString(),td); mDataTable.DefaultView.Sort=oldSort;
}
}
catch( System.Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex.Message );
} }
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;namespace ImportToTreeView
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class frmDemo : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnImport;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TreeView tvList;
private System.Windows.Forms.DataGrid dgList;
public frmDemo()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.tvList = new System.Windows.Forms.TreeView();
this.btnImport = new System.Windows.Forms.Button();
this.dgList = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dgList)).BeginInit();
this.SuspendLayout();
//
// tvList
//
this.tvList.Dock = System.Windows.Forms.DockStyle.Left;
this.tvList.ImageIndex = -1;
this.tvList.Location = new System.Drawing.Point(0, 0);
this.tvList.Name = "tvList";
this.tvList.SelectedImageIndex = -1;
this.tvList.Size = new System.Drawing.Size(232, 381);
this.tvList.TabIndex = 0;
//
// btnImport
//
this.btnImport.Location = new System.Drawing.Point(424, 352);
this.btnImport.Name = "btnImport";
this.btnImport.TabIndex = 1;
this.btnImport.Text = "导入";
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
//
// dgList
//
this.dgList.DataMember = "";
this.dgList.Dock = System.Windows.Forms.DockStyle.Top;
this.dgList.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgList.Location = new System.Drawing.Point(232, 0);
this.dgList.Name = "dgList";
this.dgList.Size = new System.Drawing.Size(280, 336);
this.dgList.TabIndex = 2;
//
// frmDemo
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(512, 381);
this.Controls.Add(this.dgList);
this.Controls.Add(this.btnImport);
this.Controls.Add(this.tvList);
this.Name = "frmDemo";
this.Text = "frmDemo";
((System.ComponentModel.ISupportInitialize)(this.dgList)).EndInit();
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new frmDemo());
} protected override void OnLoad(EventArgs e)
{
try
{
InitData();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
} //模拟的数据源
private DataTable _dataSource = null; /// <summary>
/// 初始化
/// </summary>
private void InitData()
{
//Init Schema
_dataSource = new DataTable();
_dataSource.Columns.Add("Master",typeof(string));
_dataSource.Columns.Add("Sub",typeof(string));
//Init Data
_dataSource.Rows.Add(new object[]{"车类","四轮车"});
_dataSource.Rows.Add(new object[]{"四轮车","汽车"});
_dataSource.Rows.Add(new object[]{"汽车","卡车"});
_dataSource.Rows.Add(new object[]{"汽车","轿车"});
_dataSource.Rows.Add(new object[]{"食品","生食品"});
_dataSource.Rows.Add(new object[]{"生食品","猪肉"});
_dataSource.Rows.Add(new object[]{"生食品","牛肉"});
_dataSource.Rows.Add(new object[]{"车类","二轮车"});
_dataSource.Rows.Add(new object[]{"二轮车","自行车"}); //Binding Data
this.dgList.DataSource = _dataSource;
}
/// <summary>
/// 导入到TreeView
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnImport_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Debug.Assert(_dataSource != null,"数据源为空!");
tvList.Nodes.Clear(); //寻找所有的根节点记录
ArrayList nodes = new ArrayList();
ArrayList nodeNames = new ArrayList();
for( int i=0; i<_dataSource.Rows.Count; i++ )
{//添加第一级节点 DataRow row = _dataSource.Rows[i];
string name = row.IsNull("Master") ? "": row["Master"].ToString();
if ( nodeNames.Contains(name)) continue;
string filter = string.Format("Sub='{0}'",name);
if ( _dataSource.Select(filter).Length == 0 )
{//是一个根节点,加入到节点集合中
TreeNode node = new TreeNode(name);
node.Tag = row;
filter = string.Format("Master='{0}'",row["Master"]);
foreach(DataRow dr in _dataSource.Select(filter))
{
name = dr.IsNull("Sub") ? "": dr["Sub"].ToString();
TreeNode child = new TreeNode(name);
child.Tag = dr;
node.Nodes.Add(child);
nodeNames.Add(child.Text);
}
nodes.Add(node);
nodeNames.Add(node.Text);
}
}
foreach(TreeNode nd in nodes)
CreateNode(nd); tvList.BeginUpdate();
foreach(TreeNode node in nodes)
tvList.Nodes.Add(node);
tvList.EndUpdate();
}
/// <summary>
/// 递归构造树
/// </summary>
/// <param name="nd"></param>
private void CreateNode(TreeNode nd)
{
foreach(TreeNode node in nd.Nodes)
{
DataRow row = node.Tag as DataRow;
string filter = string.Format("Master='{0}'",row["Sub"]);
DataRow[] childs = _dataSource.Select(filter);
foreach(DataRow dr in childs)
{
string name = dr.IsNull("Sub") ? "": dr["Sub"].ToString();
TreeNode tn = new TreeNode(name);
tn.Tag = dr;
node.Nodes.Add(tn);
}
CreateNode(node);
}
} }}
//获取所有项目,并通过HASHTABLE查找到父节点,
//如果没有找到就增加一个,然后在其下添加子节点
//以下是我随手写的,没测试过datatable tblsub=....//获取所有项目
hashtable tbl = new hashtable();foreach(datarow r in tblsub.rows)
{
string master=r["master"];
string name=r["sub"];
TreeNode ParentNode=(TreeNode)tbl[master]; //查找父节点
if (ParentNode==null)
{
//没找到父节点就增加一个,并用HASHTABLE记录,
//以建立MASTER和PARENTNODE之间的对应关系
ParentNode=new TreeNode(master);
TreeView1.Nodes.Add(ParentNode);
tbl.Add(master, ParentNode);
}
TreeNode ChildNode=new TreeNode(name);
ParentNode.Nodes.Add(ChildNode);
}