失败的方法一:
public void showTreeview()
{
string sqlContent = "SELECT monitorType,monitorContent FROM monitorcontent";
DataTable dtContent = this.getData(sqlContent);
treeContent.Nodes.Clear();
treeContent.CheckBoxes = true;
int count = dtContent.Rows.Count;
for(var i=0;i< count; i++)
{
string monitorType = dtContent.Rows[i]["monitorType"].ToString();
treeContent.Nodes.Add(monitorType);
if (monitorType == "自动监测")
{
foreach (TreeNode node in treeContent.Nodes)
{
if (node.Text == "自动监测")
{
string monitorContent = dtContent.Rows[i]["monitorContent"].ToString();
node.Nodes.Add(new TreeNode(monitorContent));
}
}
}
else if (monitorType == "人工监测")
{
foreach (TreeNode node in treeContent.Nodes)
{
if (node.Text == "人工监测")
{
string monitorContent = dtContent.Rows[i]["monitorContent"].ToString();
node.Nodes.Add(new TreeNode(monitorContent));
}
}
}
}
}
失败的方法二:
//添加父节点的方法
private void BindRoot()
{
string sqlContent = "SELECT monitorType,monitorContent FROM monitorcontent";
DataTable dtContent = this.getData(sqlContent);
treeContent.Nodes.Clear();
treeContent.CheckBoxes = true;
DataRow[] rows = dtContent.Select();//取根
foreach (DataRow dRow in rows)
{
TreeNode rootNode = new TreeNode();
rootNode.Tag = dRow;
rootNode.Text = dRow["monitorType"].ToString();
treeContent.Nodes.Add(rootNode);
// BindChildAreas(rootNode);//调用添加子节点的方法
DataRow dr = (DataRow)rootNode.Tag;//父节点数据关联的数据行
string monitorContent = (string)dr["monitorType"];
DataRow[] rows1 = dtContent.Select("monitorType=" +"'"+ monitorContent + "'");//子区域
if (rows1.Length == 0) //递归终止,区域不包含子区域时
{
return;
}
foreach (DataRow dRow1 in rows1)
{
TreeNode node = new TreeNode();
node.Tag = dRow;
node.Text = dRow["monitorContent"].ToString(); //添加子节点
rootNode.Nodes.Add(node);
}
}
}
成功了:
public void showAreaTree()
{
string sqlArea = "SELECT areaⅠ,areaⅡ FROM monitorarea";
DataTable dtArea = this.getData(sqlArea);
treeArea.Nodes.Clear();
treeArea.CheckBoxes = true;
int count = dtArea.Rows.Count;
for (int i = 0; i < count; i++)
{
if (dtArea.Rows[i]["areaⅠ"].ToString() != "" && dtArea.Rows[i]["areaⅡ"].ToString() != "")
{
string strArea = dtArea.Rows[i]["areaⅠ"].ToString() + '/' + dtArea.Rows[i]["areaⅡ"].ToString();//"监测区域I级"//"监测区域II级"
arryArea.Add(strArea);
}
}
foreach (string x in arryArea)
{
this.addNode(x, treeArea.Nodes);
}
}
public void addNode(string strTree, TreeNodeCollection treeNode)
{
string[] aryTree = strTree.Split('/');
TreeNodeCollection objRoot = treeNode;
TreeNode objNode = null; // 追加対象
foreach (string strNode in aryTree)
{
if (strNode == "") continue;
TreeNode[] objFind = objRoot.Find(strNode, false);
if (objFind.Length == 0)
{
objNode = objRoot.Add(strNode, strNode);
if (objNode.Parent != null)
{
objNode.Parent.ExpandAll();
}
objRoot = objNode.Nodes;
}
else
{
objNode = objFind[0];
objRoot = objNode.Nodes;
}
}
}
public DataTable getData(string sql)
{
MySqlDataAdapter adapter = MySQLConnect.GetMySQLDB().getAdapter(sql);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}