一、父選擇視窗
二、子視窗提供選擇FrmSelectAreas
1、資料準備:
在資料庫中有一張表Areas欄位為:AID,AName,APid;
AID為欄位地區編號,AName為地區名稱,APid為地區父級AID.
2、FrmSelectAreas表單中,遞迴遍曆綁定資料
View Code
1 void BindParent() //綁定父節點 2 { 3 //添加父節點 4 TreeNode parent = new TreeNode(); 5 parent.Text = "全國"; 6 parent.Tag = 0; 7 tvAreas.Nodes.Add(parent); 8 //擷取資料集 9 List<Areas> list = SQLHelper.GetALLAreas();10 //子節點綁定11 BindChildRen(parent,list);12 parent.Expand();//展開父節點13 }14 //子節點綁定15 void BindChildRen(TreeNode parent,List<Areas> list) 16 {17 //得到父節點的AId18 int Aid = Convert.ToInt32(parent.Tag);19 //遍曆20 foreach (Areas item in list)21 {22 if (Aid == item.APid)23 {24 TreeNode tn = new TreeNode();25 tn.Text = item.AName;26 tn.Tag = item.AID;27 parent.Nodes.Add(tn);28 29 BindChildRen(tn,list);30 }31 }32 }
然後,在表單載入中BindParent();
2、擷取地區全名稱:
void GetAreasText(TreeNode tn) { if (tn.Parent != null) { GetAreasText(tn.Parent); } strSelected += tn.Text + "-"; //strSelected為表單的public欄位,用於傳給父表單資料。 }
3、單擊確認時,傳回資料,關閉當前表單
GetAreasText(tvAreas.SelectedNode);//擷取資料 strSelected = strSelected.TrimEnd('-'); if (!string.IsNullOrEmpty(strSelected)) { this.DialogResult = DialogResult.OK; }