代码
//访问数据库
public DataTable gettable(String sql)
{
SqlConnection sqlcon =null;
try
{
//得到连接字符串
String constr = "Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=sasa";
//得到连接对象
sqlcon = new SqlConnection(constr);
//打开连接
sqlcon.Open();
//获得执行对象
SqlCommand comand = new SqlCommand(sql, sqlcon);
SqlDataAdapter data = new SqlDataAdapter(comand);
DataSet set = new DataSet();
data.Fill(set);
return set.Tables[0];
}
catch (Exception ex)
{
throw ex ;
}
finally
{
//关闭连接
sqlcon.Close();
}
DataTable table = null;
//加载
private void Form1_Load(object sender, EventArgs e)
{
//查询所有数据
string sql = "select *from test ";
table = gettable(sql);
//从datea中帅选 一级菜单
DataRow[] arr = table.Select("pid =0 "); //父id
foreach(DataRow row in arr)
{
TreeNode node = new TreeNode(row["name"].ToString());
node.Tag =row["id"].ToString();
addnode(node); //是否有子节点
this.treeView1.Nodes.Add((node));
}
}
//递归 显示子节点
public void addnode(TreeNode node)
{
string id = node.Tag.ToString();
DataRow[] arr = table.Select("pid = "+ id ); //子节点
foreach (DataRow row in arr)
{
TreeNode nodenode = new TreeNode(row["name"].ToString());
nodenode.Tag = row["id"].ToString();
node.Nodes.Add(nodenode);
addnode(nodenode) ; // 子节点是否还有子节点
//递归自己调用自己必须有退出的条件否则 死循环
}
}
public DataTable gettable(String sql)
{
SqlConnection sqlcon =null;
try
{
//得到连接字符串
String constr = "Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=sasa";
//得到连接对象
sqlcon = new SqlConnection(constr);
//打开连接
sqlcon.Open();
//获得执行对象
SqlCommand comand = new SqlCommand(sql, sqlcon);
SqlDataAdapter data = new SqlDataAdapter(comand);
DataSet set = new DataSet();
data.Fill(set);
return set.Tables[0];
}
catch (Exception ex)
{
throw ex ;
}
finally
{
//关闭连接
sqlcon.Close();
}
DataTable table = null;
//加载
private void Form1_Load(object sender, EventArgs e)
{
//查询所有数据
string sql = "select *from test ";
table = gettable(sql);
//从datea中帅选 一级菜单
DataRow[] arr = table.Select("pid =0 "); //父id
foreach(DataRow row in arr)
{
TreeNode node = new TreeNode(row["name"].ToString());
node.Tag =row["id"].ToString();
addnode(node); //是否有子节点
this.treeView1.Nodes.Add((node));
}
}
//递归 显示子节点
public void addnode(TreeNode node)
{
string id = node.Tag.ToString();
DataRow[] arr = table.Select("pid = "+ id ); //子节点
foreach (DataRow row in arr)
{
TreeNode nodenode = new TreeNode(row["name"].ToString());
nodenode.Tag = row["id"].ToString();
node.Nodes.Add(nodenode);
addnode(nodenode) ; // 子节点是否还有子节点
//递归自己调用自己必须有退出的条件否则 死循环
}
}
努力 努力在努力一点