日期:2014-05-18  浏览次数:20823 次

c#winfrom 中的treeview控件问题
public void AddTree1(int AID, TreeNode pNode)
  {
  DataTable dt = new DataTable();
  dt = AccessFactory.getDataTable(string.Format("select * from Anotomical "));
  DataView dvTree = new DataView(dt);
  foreach (DataRowView row in dvTree)
  {
  TreeNode node = new TreeNode();
  node.Text = row["description"].ToString();
  node.Name = row["description_en"].ToString();
  BindSubTree1(Convert.ToInt32(row["aid"].ToString()), node);
  this.treeView1.Nodes.Add(node);
  }
  }
  private void BindSubTree1(int Aid, TreeNode PNode)
  {
  DataTable subdt = new DataTable();
  subdt = AccessFactory.getDataTable(string.Format("select * from Pathological where aid='{0}' ", Aid));
  if (subdt.Rows.Count != 0 && PNode != null)
  {
  foreach (DataRow dr in subdt.Rows)
  {
  TreeNode subNode = new TreeNode();
  subNode.Text = dr["description"].ToString();
  subNode.Name = dr["description_en"].ToString();
  BindNextSbuTree1(Convert.ToInt32(dr["aid"]), Convert.ToInt32(dr["pid"]), subNode);
  PNode.Nodes.Add(subNode);
  }
  }
  }
  private void BindNextSbuTree1(int aid, int pid, TreeNode pnode)
  {
  DataTable subdt = new DataTable();
  subdt = AccessFactory.getDataTable(string.Format("select * from SubPathological where aid='{0}' and pid='{1}'", aid, pid));
  if (subdt.Rows.Count != 0 && pnode != null)
  {
  foreach (DataRow dr in subdt.Rows)
  {
  TreeNode subnode = new TreeNode();
  subnode.Text = dr["description"].ToString();
  subnode.Name = dr["description_en"].ToString();
  // subnode.Tag = dr["aid"].ToString();
  subnode.Tag = dr["pid"].ToString();
  pnode.Nodes.Add(subnode);
  }
  }
  }

这里是我加载的treeview控件,我现在想得到选中的节点的父节点aid和子节点pid,怎么获取

------解决方案--------------------
// subnode.Tag = dr["aid"].ToString()
你把这句留下就可以了
父节点id=treeView1.SelectedNode.Parent.aid
------解决方案--------------------
首先,你得把aid和pid都得绑定到每个节点里,node.Tag就只有一个,怎么办?你直接把DataRow绑定到node.Tag上就可以了。如:node.Tag= dr;
选中某个node的时候
TreeNode node = treeView1.SelectedNode;
DataRow dr = node.Tag as DataRow; 
string aid =string.Empty();
string pid = string.Empty();
if( node.Parent!=null) //说明是子节点
{
aid = dr["aid"].ToString();
pid = dr["pid"].ToString();
}
else //根节点
{
aid=dr["aid"].ToString();
}