DataSet objDataSet = new DataSet();
public RFrmDepartment()
{
InitializeComponent();
}
private void RFrmDepartment_Load(object sender, EventArgs e)
{
string sqlCmd = "Select * from Department order by DepGrade";
DataTable dt= DbHelperSQL.GetDataTable(sqlCmd);
dt.TableName = "Department";
objDataSet.Tables.Add(dt);
TreeNode rootNode = new TreeNode("某公司部门管理");
treeView1.Nodes.Add(rootNode);
BindTreeNodeData(rootNode,"",0,"1");
}
/// <summary>
/// 将数据绑定到treeView控件上
/// </summary>
/// <param name="ParentNode">父节点</param>
/// <param name="pid">父Id(指DepId)</param>
/// <param name="Plen">父id(指DepId)长度</param>
/// <param name="level">级别</param>
private void BindTreeNodeData(TreeNode ParentNode,string pid,int Plen,string level)
{ //如果为第一级别直接添加到父节点
if (level=="1")
{
DataRow[] rows = objDataSet.Tables["Department"].Select("DepGrade=" + level);
if (rows.Length != 0)
{
foreach (DataRow dr in rows)
{
string parentId = dr["DepId"].ToString().Trim();
int len = parentId.Length;
TreeNode node = new TreeNode();
node.Text = dr["DepName"].ToString();
ParentNode.Nodes.Add(node);
string levels = (int.Parse(dr["DepGrade"].ToString()) + 1).ToString();
BindTreeNodeData(node, parentId, len, levels);
}
}
else return;
}
else //如果为非第一级别,则从第一位开始,长度为“父DepId”截取“DepId” 判断是否相等。
{
DataRow[] rows = objDataSet.Tables["Department"].Select("DepGrade=" + level);
if (rows.Length != 0)
{
foreach (DataRow dr in rows)
{
string depId = dr["DepId"].ToString().Substring(0, Plen);
if (depId == pid)
{
TreeNode node = new TreeNode();
node.Text = dr["DepName"].ToString();
string parentId = dr["DepId"].ToString().Trim();
int len = parentId.Length;
ParentNode.Nodes.Add(node);
string levels = (int.Parse(dr["DepGrade"].ToString()) + 1).ToString();
BindTreeNodeData(node, parentId, len, levels);
}
}
}
else return;
}
}
说明:本人技术水平不好,此篇专供大家指正。请大家提供更好的方法。谢谢。