核心代码:
//datatable dt 存储表(name,sex),自己写
TreeNode node1,node2;
for (int i = 0; i < dt.Rows.Count; i++)
{
if(dt.Rows[i][1].ToString().Trim()=='男')
{
node1.Nodes.Add(dt.Rows[i][0].ToString().Trim());
}
else if(dt.Rows[i][1].ToString().Trim()=='女')
{
node2.Nodes.Add(dt.Rows[i][0].ToString().Trim());
}
}
treeView1.Nodes.Add(node1);
treeView1.Nodes.Add(node2);
OK,完毕。
男女 也是从数据库取呢
@YTQ: 男女本来就是来自数据库嘛
private void Form1_Load(object sender, EventArgs e)
{
TreeNode menNode = new TreeNode();
menNode.Text = "男";
TreeNode femaleNode = new TreeNode();
femaleNode.Text = "女";
treeView1.Nodes.Add(menNode);
treeView1.Nodes.Add(femaleNode);
DataTable dt = GetUser();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
TreeNode childNode = new TreeNode();
if (dr[1].ToString()=="男")
{
childNode.Text = dr[0].ToString();
menNode.Nodes.Add(childNode);
}
else if(dr[1].ToString()=="女")
{
childNode.Text = dr[0].ToString();
femaleNode.Nodes.Add(childNode);
}
}
//展开
menNode.ExpandAll();
femaleNode.ExpandAll();
}
/// <summary>
/// 模拟从数据库 读取的数据 返回DataTable
/// </summary>
/// <returns></returns>
private DataTable GetUser()
{
DataTable dt = new DataTable();
DataColumn columnName = new DataColumn("Name", typeof(string));
DataColumn columnSex = new DataColumn("Sex", typeof(string));
dt.Columns.Add(columnName);
dt.Columns.Add(columnSex);
DataRow row = dt.NewRow();
row[0] = "张三";
row[1] = "男";
dt.Rows.Add(row);
DataRow row2 = dt.NewRow();
row2[0] = "李四";
row2[1] = "男";
dt.Rows.Add(row2);
DataRow row3 = dt.NewRow();
row3[0] = "丽力";
row3[1] = "女";
dt.Rows.Add(row3);
return dt;
}
测试结果
public void tvBind()
{
DataSet ds_BuMen = getDataSet("BuMen");
DataSet ds_BLGB = getDataSet("BLGB");
foreach (DataRow dr in ds_BuMen.Tables[0].Rows)
{
//部门表绑定,作为一级层次
TreeNode tn_origine = new TreeNode();
tn_origine.Text = dr["BMMC"].ToString();
this.tvShow.Nodes.Add(tn_origine);
//病人表绑定
DataRow[] dr_arr = ds_BLGB.Tables[0].Select("BRBM=" + int.Parse(dr["id"].ToString()));
if (dr_arr.Length > 0)
{
foreach (DataRow dr_sub in dr_arr)
{
TreeNode tn_sub = new TreeNode();
tn_sub.Text = dr_sub["BRXM"].ToString();
tn_origine.Nodes.Add(tn_sub);
}
}
}
}
Datatable 中的Filters、Comput是两个不错的东东。